在我下面的 swfit 代码中,detailTextLabel 没有显示在表格视图单元格中。我已经检查了数组以确保它不为零并且不为零。我只是不知道如何使用代码来使detailTextLabel 出现。我以前见过它出现的唯一方式是在故事板编辑器中。但我无法在我的代码中使用故事板。
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return budgets.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Dequeue a cell or create a new one if none exist
var cell = tableView.dequeueReusableCell(withIdentifier: "Cell")
if cell == nil {
cell = UITableViewCell(style: .subtitle, reuseIdentifier: "Cell")
}
let budget = budgets[indexPath.row]
cell?.textLabel?.text = budget.title
cell?.detailTextLabel?.text = "Amount: \(budget.amount!)"
// Set additional properties for the detailTextLabel if needed
cell?.detailTextLabel?.numberOfLines = 0 // Allow multiple lines if needed
cell?.detailTextLabel?.lineBreakMode = .byWordWrapping // Enable word wrapping
return cell!
}
override func viewDidLoad() {
super.viewDidLoad()
tableveiew.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
}}
创建一个 UITableViewCell 子类,以指定其样式。
class SubtitleTableViewCell: UITableViewCell {
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: .subtitle, reuseIdentifier: reuseIdentifier)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
然后注册它而不是UITableViewCell 使用:
self.tableView.register(SubtitleTableViewCell.self, forCellReuseIdentifier: "Cell")
在您的示例中,永远不会调用此代码,因为注册的单元格通常总是出列,因此您的样式不会传递到单元格对象。
if cell == nil {
cell = UITableViewCell(style: .subtitle, reuseIdentifier: "Cell")
}