TableView中的不同单元格Swift 3

作为初学者,我正在尝试使用UITableViewIOCollectionView ,如何在同一个容器中创build不同的单元格(某些单元格具有集合View和一些单元格仅包含文本或图像,…)?

例如:Appstore,顶部的单元格是一个横幅,包含宽的集合视图,第二个单元格包含一个类别,其他单元格包含标签或button。

我与swift 3一起工作,更喜欢使用故事板。

假设你知道如何创build你的自定义单元格(如果你不检查这个问题 )并实现所需的数据源方法,你应该在cellForRowAtcellForItem方法中做到这一点 – 我在代码片段中使用cellForRowAt

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // first row should display a banner: if indexPath.row == 0 { let bannerCell = tableView.dequeueReusableCell(withIdentifier: "BannerTableViewCell") as! BannerTableViewCell // ... return bannerCell } // second row should display categories if indexPath.row == 1 { let categoriesCell = tableView.dequeueReusableCell(withIdentifier: "CategoriesTableViewCell") as! CategoriesTableViewCell // ... return categoriesCell } // the other cells should contains title and subtitle: let defaultCell = tableView.dequeueReusableCell(withIdentifier: "CategoriesTableViewCell") as! TileAndSubtitleTableViewCell // ... return defaultCell } 

使其更具可读性:

你也可以定义enum来检查indexPath.row而不是将它们与ints进行比较:

 enum MyRows: Int { case banner = 0 case categories } 

现在,您可以比较可读的值:

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // first row should display a banner: if indexPath.row == MyRows.banner.rawValue { let bannerCell = tableView.dequeueReusableCell(withIdentifier: "BannerTableViewCell") as! BannerTableViewCell // ... return bannerCell } // second row should display categories if indexPath.row == MyRows.categories.rawValue { let categoriesCell = tableView.dequeueReusableCell(withIdentifier: "CategoriesTableViewCell") as! CategoriesTableViewCell // ... return categoriesCell } // the other cells should contains title and subtitle: let defaultCell = tableView.dequeueReusableCell(withIdentifier: "CategoriesTableViewCell") as! TileAndSubtitleTableViewCell // ... return defaultCell } 

希望有所帮助。