使用可重复使用的细胞只设置一次细胞的正确方法?

时间:2017-07-28 07:43:31

标签: ios swift uitableview swift3

我正在寻找在Swift中使用可重用单元格的正确方法。

如何只调用setup方法一次?

override func viewDidLoad() {
    super.viewDidLoad()
    self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "AwesomeCell")
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = self.tableView.dequeueReusableCell(withIdentifier: "AwesomeCell") as UITableViewCell? ?? UITableViewCell()
    self.setup(cell: cell)  // I want this to be called only once
    cell.textLabel?.text = self.data[indexPath.row]
    return cell
}

func setup(cell: UITableViewCell) {
    cell.accessoryType = .disclosureIndicator
}

谢谢。

2 个答案:

答案 0 :(得分:1)

如果您在课程中注册了您的单元格,那么您应该将其放在单元格的init(style:reuseIdentifier:)初始值设定项中。当你调用dequeueReusableCell(withIdentifier:for:)时,这是被调用的初始化程序,表视图无法重用它。

如果您使用Xib注册了单元格,请使用单元格init(coder:)

答案 1 :(得分:-1)

在班级CrimeHolder中。试试这个:

UITableViewCell

如果要在故事板或xib上创建单元格。您可以转到附件属性并选择Disclosure Indicator

enter image description here