swift - 如何正确出列代码中的字幕 UITableViewCell?

标签 swift uitableview 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
}

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

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

到目前为止,在没有 Interface Builder 定义原型(prototype)单元格样式的情况下,用纯代码创建非 .default 样式单元格似乎是不可能的。我能想到的最接近的是这个 answer ,它注意到了同样的问题。我发现的所有其他问题也解决了 IB 问题或自定义单元格问题。

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

最佳答案

我测试了它,它有效。我以为你想子类化 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
    }

}

enter image description here

关于swift - 如何正确出列代码中的字幕 UITableViewCell?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41601105/

相关文章:

ios - 如何处理协议(protocol)功能覆盖的@available()?

ios - 如何在 uitableview 的 cellForRowAt 函数中按标题日期对响应进行排序

ios - 二元运算符 '<<' 不能应用于两个 'T' 操作数

ios - 如何快速绕过本地连接

iphone - iOS 使用间隔和自定义单元格制作自定义表格 View

swift - 创建像 Instagram 一样的 UITableView 来显示名称、图像和文本

iphone - 移动 UITableView 行然后选择它后,它仅在边缘变成蓝色

ios - GMSAutocompletePrediction prediction.attributedFullText 不在 swift 3.0 中给出 nsmutablestring

ios - Swift - 通过定义的点/区域检测用户绘图。

ios - 从 Swift 中的其他类调用方法