【问题标题】:SWIFT: UITableViewCell is initialised before its properties are set in UITableViewSWIFT:在 UITableView 中设置其属性之前初始化 UITableViewCell
【发布时间】:2021-01-22 06:37:45
【问题描述】:

我有这个UITableViewCell

class TableViewCell3: UITableViewCell {
    var sectionLabel: String?
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        self.setupLabel()
    }

    func setupLabel() {
        let myTextField: UITextField = UITextField(frame: CGRect(x: 0, y: 0, width: 300.00, height: 30.00));
        // App crashes here because sectionLabel is nil
        myTextField.text = sectionLabel!
        self.contentView.addSubview(myTextField)
    }
}

如您所见,我试图在每个 UITableViewCell 中显示一个 UITextField
我试图显示的属性sectionLabel 设置在UITableView 内:

extension MoviesViewController5: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell =
            tableView.dequeueReusableCell(withIdentifier: "tableViewCell", for: indexPath) as? sectionTableCell2
            else {
                fatalError("Unable to create explore table view cell")}

        cell.sectionLabel = sectionsLabels![indexPath.row]
        return cell
    }
}

问题是UITableViewCell 在设置sectionLabel 属性之前被初始化。
所以当我尝试显示它时:

   myTextField.text = sectionLabel!

应用程序崩溃,因为它是 nil
是的,我知道我应该添加 nil 检查,但这不是重点。
POINT 是如何显示UItextField AFTER 设置sectionLabel 属性。

【问题讨论】:

  • 为什么不在sectionLabel上使用didSet,然后它会添加值。此外,您不需要解开该值,因为您可以将 nil 放入 .text 值中。

标签: ios swift uitableview uitextfield tvos


【解决方案1】:

最好在初始化程序中设置UITextfield,并在sectionLabel 更新时设置其文本。

class TableViewCell3: UITableViewCell {

    private var myTextField: UITextField?

    var sectionLabel: String? {
        didSet {
             self.myTextField?.text = self.sectionLabel
        }
    }
 
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        self.setupLabel()
    }

    func setupLabel() {
        myTextField = UITextField(frame: CGRect(x: 0, y: 0, width: 300.00, height: 30.00));
        self.contentView.addSubview(myTextField!)
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-20
    • 1970-01-01
    • 1970-01-01
    • 2012-12-15
    • 1970-01-01
    • 2015-04-08
    • 1970-01-01
    相关资源
    最近更新 更多