如何正确使代码中的字幕 UITableViewCell 出队?

Spa*_*het 3 uitableview swift swift3

我正在尝试用纯代码创建一个带有常规非自定义.subtitle单元格的 UITableView。然而,下面的代码从来没有给我一个带有正确的单元格detailTextLabel,而是选择一个.default单元格。

public var cellIdentifier: String { return "wordsCell" }
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell: UITableViewCell
    if let newCell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) {
        // Always succeeds, so it never goes to the alternative.
        cell = newCell
    }
    else {
        // This is never reached.
        cell = UITableViewCell(style: .subtitle, reuseIdentifier: cellIdentifier)
    }

    let word = wordAtIndexPath(indexPath: indexPath)
    cell.textLabel?.text = word.text
    cell.detailTextLabel?.text = word.subText

    return cell
}
Run Code Online (Sandbox Code Playgroud)

这显然是因为即使当前没有可用的单元格,dequeueReusableCell(withIdentifier:)实际上也不会返回。nil相反,.default如果没有创建任何单元格,它总是返回 a。

另一种选择dequeueReusableCell(withIdentifier:for:)也总是成功,所以这也行不通。

到目前为止,.default如果没有 Interface Builder 来定义原型单元格的样式,用纯代码创建非样式单元格似乎是不可能的。我能想到的最接近的是这个答案,它注意到了同样的问题。我发现的所有其他问题也涉及 IB 问题或自定义单元格。

有谁知道如何.subtitle在不使用 Interface Builder 的情况下使表视图的单元格出队?

mat*_*mat 5

我测试了它并且它有效。我以为你想子类化UItableViewCell,但在这种情况下你不必注册单元格。

class TableViewController: UITableViewController {

    let wordAtIndexPath = ["one", "two", "three"]
    let cellId = "cellId"
    override func viewDidLoad() {
        super.viewDidLoad()

    }

    // MARK: - Table view data source

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

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return wordAtIndexPath.count
    }


    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let word = wordAtIndexPath[indexPath.row]
        let cell: UITableViewCell = {
            guard let cell = tableView.dequeueReusableCell(withIdentifier: cellId) else {
                return UITableViewCell(style: UITableViewCellStyle.subtitle, reuseIdentifier: cellId)
            }    
            return cell
        }()

        cell.textLabel?.text = "My cell number"
        cell.detailTextLabel?.text = word
        return cell
    }

}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述