自定义静态单元格

时间:2017-05-23 09:25:18

标签: swift uitableview

我有很多自定义单元格(xib文件+ UITableViewCell的swift子类),在许多场景中,我将它们用作动态单元格,一切运行良好(注册单元格,出列等)。

当我需要一个也可以使用这些单元格的静态tableView时,我的问题就出现了。我不能也不想用故事板来实现这个目标,因为我失去了可重用性。

我尝试过类似下面的内容,但它显示的是UITableViewCell,而不是我在xib CustomCell中的设计。看起来它不会从笔尖加载单元格的子视图。

private lazy var cells: [UITableViewCell] = [
    CustomCell1(),
    CustomCell2(),
    CustomCell3(),
]

override func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return cells.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    return cells[indexPath.row]
}

如何以编程方式使用静态自定义单元格创建UITableView

修改 @thedp的答案。自定义单元格设计如下。这只是一个例子:

final class CustomCell: UITableViewCell {
    @IBOutlet weak private var titleLabel: UILabel!
    @IBOutlet weak private var textView: MyCustomTextView!
    @IBOutlet weak private var doneButton: MyCustomButton!
    func configureCell(with: ...) { ... }
}

1 个答案:

答案 0 :(得分:0)

1)注册单元格,就像动态UITableView一样。

2)设置UITableView的数据源

3)在私有懒惰var单元格中存储单元格标识符:[UITableViewCell]而不是分配的单元格

4)然后再做下一步

override func tableView(_ tableView: UITableView,
    cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cellIdentifer = cells[indexPath.row]
    let cell = tableView.dequeueReusableCell(withIdentifier:
    cellIdentifer, for: indexPath)
    return cell
}

您还可以在viewDidLoad()方法中将单元格出列并将它们存储到数组中。但是dequeueReusableCell是必需的,你可以从类

中分配它们