UITextField in custom UITableViewCell unexpectedly found nil

喜夏-厌秋 提交于 2019-12-02 04:26:21

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.

Update

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

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

Then in WalletTableViewCell update amountTextFieldEntered to:

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

And finally update delegate implementation:

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 = ""

    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!