uitableview - UITableViewCells 的不同 - 重复模式

标签 uitableview swift custom-cell

我有一个 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)单元):

  1. 打开 Storyboard,然后选择第一个单元格(确保选择 UITableViewCell,而不是其内容 View )
  2. 在 Storyboard右侧的属性检查器中,输入自定义标识符以在标记为重用标识符的框中标识此单元格(在本例中,我将其命名为>单元格1)
  3. 对其他三个单元格重复此操作(这些后续单元格将具有标识符cell2、cell3 和 cell4
  4. 返回 UITableViewDataSource 类,重写函数 tableView: cellForRowAtIndexPath
  5. 在此函数中,获取 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/

相关文章:

ios - 在自定义单元格内动态添加标签

ios - 如何实现具有多个单元格的 UICollectionVIew

ios - 今天扩展在按钮事件后显示 "unable to load"(iOS)

ios - Swift:在 TableView Prototype Cell 中获取 Label 以显示多行(自动换行)

带有事件对象的 iOS 事件总线库?

ios - 引用 Objective-C 代码构建 Swift 框架

swift - 自定义 TableViews + CustomCell

c# - Xamarin.iOS 上的 sqlite 中的缓慢 SELECT

ios - TableView 多单元格不起作用,由于信号 9 而终止

ios - swift 中的 alertControllers