无法为 TableView 的自定义单元格设置任何属性。此外,当我在 cellsForRowAt 函数中填充 table 时,它 returns 为空 table

Not able to set any properties to the custom cell for TableView. Also, when i populate the table in cellsForRowAt function it returns empty table

无法为 table 视图的自定义单元格设置属性。 此外,无法在 cellForRowAt 函数中为自定义单元格赋值。 我正在使用 swift 5 和 xcode 10.2

import UIKit
class ContainerViewController: UIViewController, UITableViewDelegate,     UITableViewDataSource {
    let CellId = "CellId"
    let tableView : UITableView = {
        let tv = UITableView()
        tv.allowsSelection = false
        tv.separatorStyle = .none
        return tv
    }()

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: CellId, for: indexPath) as! Cell
        //cell.labelView.textColor = .red -- tried to set color here
        cell.labelView.text = "Label \(indexPath.row)" // this code doesn't seems to work
        return cell
    }
}

//- Custom Cell Class
class Cell: UITableViewCell{
    let cellView : UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.red // -- this property doesn't reflect. Also, i want to add shadow to this view any suggestions?
        return view
    }()

    let labelView: UILabel = {
        let label = UILabel()
        label.textColor = UIColor.black // -- this property doesn't reflect
        label.font = UIFont.boldSystemFont(ofSize: 16) // -- this property doesn't reflect
        return label
    }()

    func setUpCell() {
        //-- Also tried to set properties here but no luck
        //backgroundColor = UIColor.yellow
        //labelView.textColor = UIColor.black
        addSubview(cellView)
        cellView.addSubview(labelView)
        //cellView.backgroundColor = .green
    }
}

我也想为这个新的自定义单元格添加约束。

尝试使用 contentView.addSubview(cellView) 而不是 addSubview(celliIew)

因为你想使用自动布局约束,确保你设置 cellView. translatesAutoResizingMaskIntoConstraints = false (标签视图相同)

然后就可以开始了

NSLayoutConstraints.activate([
cellView.topAnchor.constraint(equalTo: contentView.topAnchor),
cellView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor),
cellView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
cellView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),

... Setup label constraints ...
)]