具有 2 个部分的表格视图,用于单元格的不同设计
tableview with 2 sections different design for cells
我需要 2 个在同一个屏幕上有 2 个 table(每个 table 的单元格设计不同)。
我不确定我是否应该在同一个视图中使用 2 tables(滚动现在弄乱了)或者 table 有 2 个部分并设计 de cells每个部分都不同。
我还没有找到任何带有 table 视图的示例,该视图包含 2 个部分并且两个部分中的单元格设计不同。
可能吗?
或者我应该尝试用 2 个不同的 tables 解决吗?
I haven't managed to find any example with a table view with 2 sections and different design of cells in the 2 sections. Is it possible?
是的,这是可能的:)
这是您使用 UITableViewDataSource
协议中的方法 tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
的地方。
你检查一下你要 return UITableViewCell
的子类的哪个部分,创建一个实例,也许填充它,然后你 return 那个。
所以你需要这样才能工作。
- 使用 NIB 文件创建
UITableViewCell
的多个子类。
例如,在 viewDidLoad()
中,您可以像这样注册 NIB:
tableView.registerNib(UINib(nibName: "Cell1", bundle: nil), forCellReuseIdentifier: "Cell1")
tableView.registerNib(UINib(nibName: "Cell2", bundle: nil), forCellReuseIdentifier: "Cell2")
在 tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath)
中,您检查要求的部分和 return 正确的子类,就像这样(有改进的余地:-)):
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
switch indexPath.section {
case 0:
if let cell1 = tableView.dequeueReusableCellWithIdentifier("Cell1") as? Cell1 {
//populate your cell here
return cell1
}
case 1:
if let cell2 = tableView.dequeueReusableCellWithIdentifier("Cell2") as? Cell2 {
//populate your cell here
return cell2
}
default:
return UITableViewCell()
}
return UITableViewCell()
}
希望对您有所帮助
我需要 2 个在同一个屏幕上有 2 个 table(每个 table 的单元格设计不同)。
我不确定我是否应该在同一个视图中使用 2 tables(滚动现在弄乱了)或者 table 有 2 个部分并设计 de cells每个部分都不同。
我还没有找到任何带有 table 视图的示例,该视图包含 2 个部分并且两个部分中的单元格设计不同。
可能吗?
或者我应该尝试用 2 个不同的 tables 解决吗?
I haven't managed to find any example with a table view with 2 sections and different design of cells in the 2 sections. Is it possible?
是的,这是可能的:)
这是您使用 UITableViewDataSource
协议中的方法 tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
的地方。
你检查一下你要 return UITableViewCell
的子类的哪个部分,创建一个实例,也许填充它,然后你 return 那个。
所以你需要这样才能工作。
- 使用 NIB 文件创建
UITableViewCell
的多个子类。 例如,在
viewDidLoad()
中,您可以像这样注册 NIB:tableView.registerNib(UINib(nibName: "Cell1", bundle: nil), forCellReuseIdentifier: "Cell1") tableView.registerNib(UINib(nibName: "Cell2", bundle: nil), forCellReuseIdentifier: "Cell2")
在
tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath)
中,您检查要求的部分和 return 正确的子类,就像这样(有改进的余地:-)):func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { switch indexPath.section { case 0: if let cell1 = tableView.dequeueReusableCellWithIdentifier("Cell1") as? Cell1 { //populate your cell here return cell1 } case 1: if let cell2 = tableView.dequeueReusableCellWithIdentifier("Cell2") as? Cell2 { //populate your cell here return cell2 } default: return UITableViewCell() } return UITableViewCell() }
希望对您有所帮助