繁体   English   中英

我在 cellForRowAt 遇到错误,我不知道为什么

[英]Im getting an error at cellForRowAt and im not sure why

我在cellForRowAt函数中遇到错误

无法将“产品”类型的值分配给“字符串”类型?

cell.textLabel?.text = product是导致此错误的问题吗?

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell()
        let product = items[indexPath.row]
        cell.textLabel?.text = product

        cell.contentView.backgroundColor = UIColor(red:0.92, green:0.92, blue:0.92, alpha:1.0)
        cell.textLabel?.textColor = UIColor(red:0.13, green:0.13, blue:0.13, alpha:1.0)
        tableView.separatorColor = UIColor(red:0.13, green:0.13, blue:0.13, alpha:1.0)


        return cell
    }

cell.textLabel?.text = product尝试做product.itemproduct.priceproduct.salesPrice.

cell.textLabel?.text需要一个字符串,您正在设置的是另一种类型。

cell.textLabel?.text只能显示一个String对象,不能显示其他对象。

它将是product.itemproduct.priceproduct.salesPrice或全部在一行中。 (根据您的要求)。

确保product的价值不为零。

cell.textLabel?.text = "\(product.item) \(product.price) \(product.salesPrice)"

你可以试试这个完整的代码:

class ViewController: UIViewController, UIAdaptivePresentationControllerDelegate {

    @IBOutlet weak var tableView: UITableView!

    var items:[Product]? = []

    // VIEW LOAD
    override func viewDidLoad() {
        super.viewDidLoad()

        if #available(iOS 13.0, *) {
            self.isModalInPresentation = true
        }

        getData()
    }
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(true)
        getData()
    }

    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(true)
        storeData()
    }
    override var prefersStatusBarHidden: Bool {
        return true
    }
    // ADD ITEMS
    @IBAction func addButtonTapped(_ sender: Any) {
        let alert = UIAlertController(title: "Product Information", message: nil, preferredStyle: .alert)
        alert.addTextField { (itemTextField) in
            itemTextField.placeholder = "Item"
        }
        alert.addTextField { (priceTextField) in
            priceTextField.placeholder = "Price"
        }

        alert.addTextField { (salePriceTextField) in
            salePriceTextField.placeholder = "Sale Price"
        }

        let action = UIAlertAction(title: "Add", style: .default) { (_) in
            let item = alert.textFields?[0].text ?? ""
            let price = alert.textFields?[1].text ?? ""
            let salesPrice = alert.textFields?[2].text ?? ""

            let product = Product(item: item, price: price, salesPrice: salesPrice)
            self.addProduct(product)
        }

        alert.addAction(action)
        present(alert, animated: true)
        storeData()

    }

    func addProduct(_ product: Product) {
        let index = 0
        items?.insert(product, at: index)

        let indexPath = IndexPath(row: index, section: 0)
        tableView.insertRows(at: [indexPath], with: .left)
        storeData()
    }

    //STORE DATA
    func storeData() {
        UserDefaultUtil.saveData(products: items)
    }

    func getData() {
        items = UserDefaultUtil.loadProducts()

    }

}

//EXTENSION
extension ViewController: UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

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

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell()
        let product = items![indexPath.row]
        cell.textLabel?.text = "\(product.item!) \(product.price) \(product.salesPrice)"

        cell.contentView.backgroundColor = UIColor(red:0.92, green:0.92, blue:0.92, alpha:1.0)
        cell.textLabel?.textColor = UIColor(red:0.13, green:0.13, blue:0.13, alpha:1.0)
        tableView.separatorColor = UIColor(red:0.13, green:0.13, blue:0.13, alpha:1.0)


        return cell
    }

    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        guard editingStyle == .delete else { return }
        items?.remove(at: indexPath.row)
        tableView.deleteRows(at: [indexPath], with: .fade)
        storeData()
    }
}

class UserDefaultUtil {

    private static let Key = "savedData"

    private static func archivePeople(people : [Product]) -> NSData {

        return NSKeyedArchiver.archivedData(withRootObject: people as NSArray) as NSData
    }

    static func loadProducts() -> [Product]? {

        if let unarchivedObject = UserDefaults.standard.object(forKey: Key) as? Data {

            return NSKeyedUnarchiver.unarchiveObject(with: unarchivedObject as Data) as? [Product]
        }

        return nil
    }

    static func saveData(products : [Product]?) {
        let archivedObject = archivePeople(people: products!)
        UserDefaults.standard.set(archivedObject, forKey: Key)
        UserDefaults.standard.synchronize()
    }

}

class Product: NSObject, NSCoding {
    var item: String?
    var price: String?
    var salesPrice: String?

    required init(item:String, price:String, salesPrice: String) {
        self.item = item
        self.price = price
        self.salesPrice = salesPrice
    }

    required init(coder aDecoder: NSCoder) {
        self.item = aDecoder.decodeObject(forKey: "item") as? String
        self.price = aDecoder.decodeObject(forKey: "price") as? String
        self.salesPrice = aDecoder.decodeObject(forKey: "salesPrice") as? String
    }

    public func encode(with aCoder: NSCoder) {
        aCoder.encode(item, forKey: "item")
        aCoder.encode(price, forKey: "price")
        aCoder.encode(salesPrice, forKey: "salesPrice")
    }
}

首先重用细胞。

切勿使用默认初始值设定项创建单元格。

为 Interface Builder 中的单元格分配一个标识符(例如MainCell ),然后替换

let cell = UITableViewCell()

let cell = tableView.dequeueReusableCell(withIdentifier: "MainCell", for: indexPath)

错误非常明显。 正如其他答案中已经提到的,您必须将Product属性值分配给标签

cell.textLabel?.text = product.title

不要使用默认初始值设定项创建单元格

在界面构建器中为 tableview 的单元格分配一个标识符

let cell = tableview.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

您必须将 Product 的属性分配给标签的文本

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableview.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        let product = items[indexPath.row]
        cell.textLabel?.text = product.price // product.item, product.salesPrice
        return cell
    }

暂无
暂无

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

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