自定义UITableViewCell中的UITextField意外找到nil [英] UITextField in custom UITableViewCell unexpectedly found nil

查看:58
本文介绍了自定义UITableViewCell中的UITextField意外找到nil的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 TableView ,其中的自定义单元格中有一个 TextField ,不幸的是,我得到了一个 Thread 1:致命错误:在使用它们时,在展开一个可选值时意外发现nil (按return键或触摸textField外部的屏幕以移出占位符)。

I have a TableView with custom cells that have a TextField inside, unfortunately I get a Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value when I use them (press return or touch the screen outside the textField to get out of the placeholder).

这是我的代码:

class WalletTableViewController: UIViewController, UITextFieldDelegate {

    var cryptosArray: [Cryptos] = []

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.delegate = self

        loadCryptoArray()
    }

    func loadCryptoArray() {

        if UserDefaults.standard.object(forKey: "cryptosArray") != nil {
            if let decoded = UserDefaults.standard.object(forKey: "cryptosArray") as? Data? {
               let decodedCryptoArray = NSKeyedUnarchiver.unarchiveObject(with: decoded!) as! [Cryptos]
               cryptosArray = decodedCryptoArray
        }
    } 
}

}

TableView 扩展名:

The TableView extension :

extension WalletTableViewController: UITableViewDelegate, UITableViewDataSource {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return cryptosArray.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let crypto = cryptosArray[indexPath.row]

        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! WalletTableViewCell
        cell.setCrypto(crypto: crypto)
        cell.delegate = self
        cell.amountTextField.delegate = self

        return cell
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 85
    }
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            cryptosArray.remove(at: indexPath.row)
            tableView.deleteRows(at: [indexPath], with: .fade)

            let userDefaults = UserDefaults.standard
            let encodedData : Data = NSKeyedArchiver.archivedData(withRootObject: cryptosArray)
            userDefaults.set(encodedData, forKey: "cryptosArray")
            userDefaults.synchronize()
        }
    }
}

这是 TextField

This is the delegate function for the TextField:

extension WalletTableViewController: CryptoCellDelegate {
    func cellAmountEntered(_ sender: Any) {
        if WalletTableViewCell().amountTextField.text == "" {
            return
        }
        let str = WalletTableViewCell().amountTextField.text

        let formatter = NumberFormatter()
        formatter.locale = Locale(identifier: "en_US")
        let dNumber = formatter.number(from: str!)
        let nDouble = dNumber!
        let eNumber = Double(truncating: nDouble)

        WalletTableViewCell().amountLabel.text = String(format:"%.8f", eNumber)

      UserDefaults.standard.set(WalletTableViewCell().amountLabel.text, forKey: "bitcoinAmount")
        WalletTableViewCell().amountTextField.text = ""

    }
}

自定义单元文件:

protocol CryptoCellDelegate {
    func cellAmountEntered(_ sender: Any)
}

class WalletTableViewCell: UITableViewCell {

    @IBOutlet weak var cryptoNameLabel: UILabel!
    @IBOutlet weak var amountLabel: UILabel!

    @IBOutlet weak var amountTextField: UITextField!

    var cryptoItem: Crypto!
    var delegate: CryptoCellDelegate?

    func setCrypto(crypto: Cryptos) {

        cryptoNameLabel.text = crypto.name
    }

    @IBAction func amountTextFieldEntered(_ sender: Any) {
        delegate?.cellAmountEntered((Any).self)
    }

}

TableView 拥有用户想要的单元格,因此这取决于数组创建单元格的对象。

The TableView has as many cells as the user wants, so this is depending on the array of objects that create the cells.

我想我在某处有 delegate 问题?我对 UITableView 很陌生,所以这是一个很大的挑战,请原谅任何愚蠢的错误:)

I guess I have a delegate problem somewhere? I am quite new to UITableView so this has been quite a challenge, forgive any stupid blunder :)

PS:我试图通过删除键盘函数和无关的内容来使代码简短,请告诉我是否需要其他东西。

PS: I've tried to keep the code short by removing keyboard functions and unrelated stuff, please tell me if you need something else.

推荐答案

在使用 WalletTableViewCell()的任何地方,您都在创建 WalletTableViewCell 。发生崩溃是因为您是通过编程方式创建的,而 WalletTableViewCell 是使用情节提要进行设计的,并且由于您没有使用情节提要进行实例化,因此 @IBOutlet s尚未设置,因此 nil

Everywhere where you use WalletTableViewCell() you are creating a new instance of the WalletTableViewCell. The crash happens because you are creating it programmatically, while WalletTableViewCell was designed using storyboards, and since you did not instantiated it using storyboards, @IBOutlets have not been set, therefore are nil.

更新 >

尝试使用此功能修复它。将 CryptoCellDelegate 更新为此:

Try to fix it using this. Update CryptoCellDelegate to this:

protocol CryptoCellDelegate {
    func cellAmountEntered(_ walletTableViewCell: WalletTableViewCell)
}

然后在 WalletTableViewCell中 amountTextFieldEntered 更新为:

@IBAction func amountTextFieldEntered(_ sender: Any) {
    delegate?.cellAmountEntered(self)
}

最后更新委托实现:

extension WalletTableViewController: CryptoCellDelegate {
    func cellAmountEntered(_ walletTableViewCell: WalletTableViewCell) {
        // now you can use walletTableViewCell to access the cell that called the delegate method
        if walletTableViewCell.amountTextField.text == "" {
            return
        }
        let str = walletTableViewCell.amountTextField.text

        let formatter = NumberFormatter()
        formatter.locale = Locale(identifier: "en_US")
        let dNumber = formatter.number(from: str!)
        let nDouble = dNumber!
        let eNumber = Double(truncating: nDouble)

        walletTableViewCell.amountLabel.text = String(format:"%.8f", eNumber)

        UserDefaults.standard.set(walletTableViewCell.amountLabel.text, forKey: "bitcoinAmount")
        walletTableViewCell.amountTextField.text = ""

    }
}

这篇关于自定义UITableViewCell中的UITextField意外找到nil的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆