UITextField in custom UITableViewCell unexpectedly found nil

前端 未结 1 441
猫巷女王i
猫巷女王i 2021-01-25 08:20

I have a TableView with custom cells that have a TextField inside, unfortunately I get a Thread 1: Fatal error: Unexpectedly found nil while un

1条回答
  •  走了就别回头了
    2021-01-25 08:49

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

    0 讨论(0)
提交回复
热议问题