在不使用故事板的表格视图单元格中显示详细文本标签

问题描述 投票:0回答:1

在我下面的 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")
  }}
swift tableview cell detailtextlabel
1个回答
0
投票

创建一个 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")
}
© www.soinside.com 2019 - 2024. All rights reserved.