TableView中的不同单元格Swift 3
作为初学者,我正在尝试使用UITableView
和IOCollectionView
,如何在同一个容器中创build不同的单元格(某些单元格具有集合View和一些单元格仅包含文本或图像,…)?
例如:Appstore,顶部的单元格是一个横幅,包含宽的集合视图,第二个单元格包含一个类别,其他单元格包含标签或button。
我与swift 3一起工作,更喜欢使用故事板。
假设你知道如何创build你的自定义单元格(如果你不检查这个问题 )并实现所需的数据源方法,你应该在cellForRowAt
或cellForItem
方法中做到这一点 – 我在代码片段中使用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 }
希望有所帮助。
- UITableViewAutomaticDimension不能工作,直到滚动
- App crush:由于未捕获的exception“NSInternalInconsistencyException”而终止应用程序,原因是:“无效的更新:节0中的行数无效
- 如何使用writeToFile将图像保存在文档目录中?
- 将可滚动button添加到滚动视图
- CoreBluetooth didDiscoverPeripheral不在Swift中调用
- Swift不转换Objective-C NSError **抛出
- 在xcode8中找不到ModuleName-Swift.h文件
- 如何让相机跟随玩家?
- RestKit.h从来没有在Xcode项目中find