【问题标题】:Im getting an error at cellForRowAt and im not sure why我在 cellForRowAt 收到错误,我不知道为什么
【发布时间】:2020-03-20 09:35:21
【问题描述】:

我在函数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, productProduct 的一个实例,但您试图将它分配给一个需要String 实例的属性。也许使用Product 属性,例如cell.textLabel?.text = product.item
  • 像 cell.textLabel?.text = product.item 或 product.price 一样使用
  • 我得到一个线程 1:当我运行它时发出信号 SIGABRT
  • 让 product = items[indexPath.row] 在下一行打印 product 看看它的值是多少
  • ^这不起作用,我刚试过@vijeesh

标签: ios swift swift4 swift5


【解决方案1】:

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

cell.textLabel?.text 期待一个字符串,您设置的是另一种类型。

【讨论】:

  • 二元运算符“/”不能应用于两个“字符串”操作数。这就是我得到的错误
  • 现在检查答案。我修改了,不会给你造成混淆。
  • 我得到一个线程 1:当我运行它并且只使用 cell.textLabel?.text = product.item 时出现信号 SIGABRT 错误
  • @MG3 你想在文本字段中打印什么?
  • 我在顶部贴了一张图片给你,这就是我想要的样子
【解决方案2】:

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")
    }
}

【讨论】:

  • 请设置所有异常断点并再次运行。这将标记确切的异常点。
  • 什么意思?
  • 似乎产品的价值为零。在将值设置为标签之前,请确保 product 不为零。
  • 我如何确保它不是?我从来没有把它设置为 nil
【解决方案3】:

首先重用单元格。

切勿使用默认初始化程序创建单元格。

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

let cell = UITableViewCell()

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

错误很明显。正如在其他答案中已经提到的,您必须将Productproperty 的值分配给标签

cell.textLabel?.text = product.title

【讨论】:

    【解决方案4】:

    不要使用默认初始化器创建单元格

    在界面生成器中为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
        }
    

    【讨论】:

      猜你喜欢
      • 2017-11-23
      • 2019-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-02
      • 2020-08-02
      相关资源
      最近更新 更多