ios - 使用 UICollectionViews 创建动态和多特征

标签 ios uitableview uicollectionview

我有兴趣创建一个 View ,其中包含用户可以向下滚动查看的多个功能,即图片、描述、评论、轮播等。我知道 UICollectionView 能够提供此功能布局类型。我最初认为 UITableViews 是最好的方法。

我看过一些教程和 GitHub 存储库,但其中大部分只使用标准网格布局中的 UICollectionView。我也看过 IGListKitInstagram 和链接到它的一些教程使用。

我的目标是获得类似 KitchenStories 应用程序的东西:

enter image description here

我想知道是否有人可以就最适合此的方向和方法向我提出建议。

最佳答案

不要尝试对任何单个 View 做太多事情,即使是 UICollectionView

您显示的屏幕有一个 UITabBarController 管理其顶级排列。当前选择的选项卡(“主页”)有一个 UINavigationController 管理其内容。

导航堆栈的顶部可能是 Collection View 或 TableView 。两者都可以在这里使用,因为元素在视觉上被布置为堆栈中的屏幕宽度行。表格 View 更简单,因为这样您就不必担心设置布局。

表格 View 有几个可见的行,每行都不同:

  • 标题/图片行(“简易海鲜饭”)
  • 评级行
  • 导出行(红心/保存/分享)
  • 评论行
  • 创作者行(我猜,因为看起来可能是头像和名字)

并且可能还有更多独特的行不在 View 中。

在您的 Storyboard中,您可以将这些行中的每一行设计为 TableView Controller 场景中的原型(prototype)行。或者您可以设计具有静态内容行的 TableView ,如果您不需要在运行时更改行的顺序或复制任何行,这会更容易。

“但是 Rob,”你说,“我无法将所有这些行都放入 Storyboard的 TableView 中!” Make the storyboard scene taller. UIKit 会在运行时调整它的大小以适合设备屏幕。

在每一行中,拖入并排列该行数据所需的任何 subview 。例如,标题/图像行需要一个 UIImageView 和一个 UILabel。评级行需要一个标签,可能是一个自定义 View 来显示和编辑星星,可能还有一个用于布局的堆栈 View 。

对于每一行,您需要一个单独的 UITableViewCell 子类,其中包含该行 View 的导出。要将数据传递给每个单元格进行显示,请使每个单元格符合协议(protocol):

protocol RecipeUsing {
    var recipe: Recipe? { get set }
}

然后,在您的 TableView Controller 中,如果您使用的是静态内容,则可以这样设置:

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = super.tableView(tableView, cellForRowAt: indexPath)
        if let user = cell as? RecipeUsing {
            user.recipe = recipe
        }
        return cell
    }

您需要一个带有 UIImageViewUILabel 导出的 RecipeTitleImageCell。像这样:

class RecipeTitleImageCell: UITableViewCell, RecipeUsing {

    @IBOutlet var label: UILabel!

    // UITableViewCell has an imageView property that's not an outlet 😭
    @IBOutlet var myImageView: UIImageView!

    var recipe: Recipe? {
        didSet {
            guard let recipe = recipe else { return }
            label.text = recipe.title
            myImageView.image = recipe.image
        }
    }
}

对于评级行,您需要这样的内容:

class RecipeRatingsCell: UITableViewCell, RecipeUsing {
    @IBOutlet var ratingControl: RatingControl!
    @IBOutlet var label: UILabel!

    var recipe: Recipe? {
        didSet {
            guard let recipe = recipe else { return }
            ratingControl.rating = recipe.ratings.reduce(0, +) / recipe.Double(ratings.count)

            if ratings.count < 5 { label.text = "Too few ratings" }
            else { label.text = "\(ratings.count) ratings" }
        }
    }
}

关于ios - 使用 UICollectionViews 创建动态和多特征,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44332184/

相关文章:

ios - SDWebImage 按钮背景图像调整大小

ios - 使用 Swift 创建 Flutter 项目

ios - 过滤数组问题

ios - 隐藏导航栏后面的第一个单元格

ios - 内在内容大小在UITableView内部的UICollectionView

ios - UICollectionView 中的单元格重叠

ios - 不知道如何使用从 Web 服务返回的 JSON 数据

ios - iOS 中 UITableView 的每个单元格的时间倒计时

ios - 滚动到 Collection View 中的项目会使应用程序崩溃

ios - 快速从数组中删除自定义类型的元素