【问题标题】:Swift - Custom textLabel in TableViewCellSwift - TableViewCell 中的自定义文本标签
【发布时间】:2019-11-26 18:48:34
【问题描述】:

目前我有一个UITableView,用户可以在其中添加cells,其中有一个textLabel

这就是我设置label的方式:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: WhishCell.reuseID, for: indexPath)
    let currentWish = self.wishList[indexPath.row]
    cell.textLabel?.text = currentWish.wishName
    cell.backgroundColor = .clear

    return cell
}

我的问题是,我如何自定义 textLabel(字体、约束、...)。我尝试在我的WishCell 类中创建一个自定义UILabel,但我无法在cellforRowAtcell.theLabel 中访问它。

希望你能理解我的问题,我非常感谢每一个帮助:)

已解决

我只是忘记了cellForRowAt 中的as! WhishCell。感谢您的所有帮助:)

【问题讨论】:

标签: ios swift uitableview


【解决方案1】:

你需要给你的单元格自定义类名

let cell = tableView.dequeueReusableCell(withIdentifier: WhishCell.reuseID, for: indexPath) as! CellName
cell.lbl.text = ////

 class CellName:UITableViewCell {
    let lbl = UILabel() 
   override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
    super.init(style: style, reuseIdentifier: reuseIdentifier) 
       lbl.backgroundColor = UIColor.red
       self.contentView.addSubview(lbl)
       // set constraints here 
    }

    required init?(coder aDecoder: NSCoder) {
       super.init(coder: aDecoder)
    }
 }

【讨论】:

  • 您可以更改字体但不能更改约束,您需要在自定义单元格中使用lbl 进行此操作
  • 任何方式我都可以在我的Class WhishCell 中创建一个customLabel,这样我就可以在cellForRowAt 中调用cell.customLabel.text = currentWish.wishName
  • 啊啊我只是个白痴...我错过了as! WhishCell!谢谢人:D
【解决方案2】:

不要强行解包。尝试使用guardif let

guard let cell = tableView.dequeueReusableCell(withIdentifier: WhishCell.reuseID, for: indexPath) as? WhishCell else{
  return UITableViewCell()
}
cell.lbl.text = "my text" 
let currentWish = self.wishList[indexPath.row]
cell.textLabel?.text = currentWish.wishName
cell.backgroundColor = .clear

return cell

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多