我有一个 UITableView
,其中包含四个不同的自定义 UITableViewCell
。我需要按如下方式重复每种细胞类型:
row 0 -> cell1
row 1 -> cell2
row 2 -> cell3
row 3 -> cell4
row 4 -> cell1
row 5 -> cell2
row 6 -> cell3
row 7 -> cell4
row 8 -> cell1
...
有什么想法可以实现这一目标吗?
最佳答案
要实现此目的,只需按照以下步骤操作(我假设您已在 Storyboard中制作了四个原型(prototype)单元):
- 打开 Storyboard,然后选择第一个单元格(确保选择
UITableViewCell
,而不是其内容 View ) - 在 Storyboard右侧的属性检查器中,输入自定义标识符以在标记为重用标识符的框中标识此单元格(在本例中,我将其命名为>单元格1)
- 对其他三个单元格重复此操作(这些后续单元格将具有标识符cell2、cell3 和 cell4
- 返回
UITableViewDataSource
类,重写函数tableView: cellForRowAtIndexPath
。 在此函数中,获取
indexPath.row
以 4 为模数 (%)。如果该值为 0,则执行tableView.dequeueReusableCellWithIdentifier("cell1")
如果是1,则替换为cell2,以此类推。在代码中,第 5 步看起来像这样 -switch indexPath.row % 4 { case 0: let cell = tableView.deqeueReusableCellWithIdentifier("cell1") case 1: let cell = tableView.deqeueReusableCellWithIdentifier("cell2") case 2: let cell = tableView.deqeueReusableCellWithIdentifier("cell3") case 3: let cell = tableView.deqeueReusableCellWithIdentifier("cell4") } return cell
只需将此代码放入步骤 4 中提到的函数中,即可构建并运行。希望这有效!
关于uitableview - UITableViewCells 的不同 - 重复模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30444957/