首页 > 解决方案 > 无法为 TableView 的自定义单元格设置任何属性。此外,当我在 cellsForRowAt 函数中填充表时,它返回空表

问题描述

无法将属性设置为表格视图的自定义单元格。此外,无法在 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
    }
}

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

标签: iosswift5

解决方案


尝试使用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 ...
)]

推荐阅读