【发布时间】:2017-02-18 19:27:42
【问题描述】:
作为初学者,我正在尝试使用 UITableView 和 IOCollectionView,如何在同一个容器?
例如:Appstore,顶部的单元格是横幅,包含宽集合视图,第二个单元格包含类别,其他包含标签或按钮。
我使用 swift 3,更喜欢使用故事板。
【问题讨论】:
标签: ios swift uitableview cells
作为初学者,我正在尝试使用 UITableView 和 IOCollectionView,如何在同一个容器?
例如:Appstore,顶部的单元格是横幅,包含宽集合视图,第二个单元格包含类别,其他包含标签或按钮。
我使用 swift 3,更喜欢使用故事板。
【问题讨论】:
标签: ios swift uitableview cells
假设您确实知道如何创建自定义单元格(如果您不检查 this question)并实现所需的数据源方法,您应该在 cellForRowAt 或 cellForItem 方法中执行此操作 - 我是在代码 sn-p- 中使用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,而不是将它们与整数进行比较:
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
}
【讨论】: