繁体   English   中英

UITableViewCell中的UILabel返回nil

[英]UILabel in UITableViewCell returns nil

我想在UIViewController中设置一个UITableView。 UITableView具有包含UILabel的UITableViewCells。

但是,UITableView.UILabels返回nil。

请查看以下代码和图像并分享您的想法。

先感谢您。

我正在用Swift5开发它。


import UIKit

class condimentTableCell: UITableViewCell {
    @IBOutlet weak var condimentName: UILabel!
}

class SandwichViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate, UITableViewDataSource, UITableViewDelegate {

    @IBOutlet weak var condimentTable: UITableView!
    @IBOutlet weak var breadSelector: UIPickerView!

    fileprivate let items:[product] = products().getData()
    fileprivate let cart:cart = Registry.instance.liveCart

    var itemNo: Int = 0
    let condiments = ["Lettuce", "Mayo", "Mustard", "Purple Onions", "Tomato"]
    let breads = ["Rye", "Sourdough", "Squaw", "Wheat", "White"]

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor(patternImage: UIImage(named: "background.png")!)
        self.breadSelector.dataSource = self
        self.breadSelector.delegate = self
        self.condimentTable.register(condimentTableCell.self, forCellReuseIdentifier: "condimentCell")
        self.condimentTable.delegate = self
        self.condimentTable.dataSource = self
    }


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

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 100
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell:condimentTableCell = tableView.dequeueReusableCell(withIdentifier: "condimentCell", for: indexPath) as! condimentTableCell
        if (cell.condimentName == nil) {
            print("nil")
        } else {
            cell.condimentName.text = condiments[indexPath.row]
        }
        print("----------------------------------------------")
        return cell
    }


    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return breads.count
    }

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return breads[row]
    }
}

模拟器

打印结果

故事板1

故事板2

删除线

self.condimentTable.register(condimentTableCell.self, forCellReuseIdentifier: "condimentCell")

您正在断开情节提要与单元的连接。

有关详细说明,请参见https://stackoverflow.com/a/44107114/669586

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM