Ios TableView Swift 3中的不同单元格
作为初学者,我正在尝试使用Ios TableView Swift 3中的不同单元格,ios,swift,uitableview,cells,Ios,Swift,Uitableview,Cells,作为初学者,我正在尝试使用UITableView和IOCollectionView,如何在同一容器中创建不同的单元格(有些单元格具有集合视图,有些单元格仅具有文本或图像,…) 例如:Appstore,顶部的单元格是横幅,包含宽集合视图,第二个单元格包含类别a,其他单元格包含标签或按钮 我使用swift 3,更喜欢使用故事板。假设您知道如何创建自定义单元格(如果您不检查)并实现所需的数据源方法,您应该在cellForRowAt或cellForItem方法中执行此操作-我在代码段中使用cellFor
UITableView
和IOCollectionView
,如何在同一容器中创建不同的单元格(有些单元格具有集合视图,有些单元格仅具有文本或图像,…)
例如:Appstore,顶部的单元格是横幅,包含宽集合视图,第二个单元格包含类别a,其他单元格包含标签或按钮
我使用swift 3,更喜欢使用故事板。假设您知道如何创建自定义单元格(如果您不检查)并实现所需的数据源方法,您应该在
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
,而不是将它们与int进行比较:
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
}
太谢谢你了,我现在就试试