我正在尝试使用纯代码中的常规非自定义 .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
}
}
关于swift - 如何正确出列代码中的字幕 UITableViewCell?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41601105/