首页 > 解决方案 > 在 UITableView 中使用编程自定义 UILabel

问题描述

我正在尝试使用UITableViewCell我以编程方式在UITableView.

UITableViewCell班级:

class PopulatedCellStyleTableViewCell: UITableViewCell {

    private let userDisplayName: UILabel = {
        let lbl = UILabel()
        lbl.font = UIFont(name: "Baskerville-Bold", size: 16)
        lbl.textColor = .purple
        lbl.textAlignment = .left
        lbl.backgroundColor = UIColor(displayP3Red: 1, green: 1, blue: 1, alpha: 0.5)
        return lbl
    }()

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        addSubview(userDisplayName)

//from a UIKit extension that allows me to easily add anchors
        userDisplayName.anchor(top: self.topAnchor, left: self.leftAnchor, bottom: self.bottomAnchor, right: self.rightAnchor, paddingTop: 5, paddingLeft: 0, paddingBottom: 5, paddingRight: 0, width: self.frame.width, height: self.frame.height, enableInsets: false)
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

UITableViewController班级:

class LoveListController: UITableViewController {

    var loveList: [String]!
    let populatedCell = "populatedCell"

    override func viewDidLoad() {
        super.viewDidLoad()
        self.tableView.register(PopulatedCellStyleTableViewCell.self, forCellReuseIdentifier: populatedCell)

    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return loveList.count
    }


    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: populatedCell, for: indexPath)

        // Configure the cell...
        cell.textLabel?.text = loveList[indexPath.row]
        return cell
    }
}

在检查调试视图层次结构时,标签加载,但实际文本呈现在 aUITableViewCellContentView而不是 myUILabel中,我不知道为什么。

如果这很容易解决或之前已经讨论过,请指出正确的方向和/或教我如何自己发现解决方案!

标签: iosswiftuitableview

解决方案


您需要投射单元格并使用您的自定义userDisplayName而不是textLabel

let cell = tableView.dequeueReusableCell(withIdentifier: populatedCell, for: indexPath) as! PopulatedCellStyleTableViewCell
cell.userDisplayName.text = loveList[indexPath.row]

另外最好添加标签contentView并用它创建约束

self.contentView.addSubview(userDisplayName)
self.userDisplayName.anchor(top: self.contentView.topAnchor .....

推荐阅读