自定义UITableViewCell中的UITextField意外发现为零

时间:2018-03-01 10:04:52

标签: ios swift uitableview delegates uitextfield

我有一个TableView内置TextField的自定义单元格,遗憾的是我得到了一个主题1:致命错误:在解包一个可选值时出乎意料地发现了nil我使用它们(按返回或触摸textField外面的屏幕以退出占位符)。

这是我的代码:

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扩展程序:

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

的委托功能
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包含与用户想要的一样多的单元格,因此这取决于创建单元格的对象的array

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

PS:我试图通过删除keyboard函数和不相关的东西来缩短代码,请告诉我你是否还需要其他东西。

1 个答案:

答案 0 :(得分:1)

您使用WalletTableViewCell()的任何地方都在创建WalletTableViewCell的新实例。发生崩溃的原因是您以编程方式创建崩溃,而WalletTableViewCell是使用故事板设计的,并且由于您没有使用故事板对其进行实例化,因此@IBOutlet尚未设置,因此nilCryptoCellDelegate

<强>更新

尝试使用此方法修复它。将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 = ""

    }
}

最后更新委托实施:

{"name":"a1", "std":"9", "year":"2017", "exam":"halfyr_T", "marks":[{"p":"45","m":"40","c":"50"}]}
{"name":"a1", "std":"9", "year":"2017", "exam":"halfyr_P", "marks":[{"p":"40","m":"28","c":"38"}]}
{"name":"a1", "std":"9", "year":"2017", "exam":"annual_T", "marks":[{"p":"40","m":"50","c":"48"}]}
{"name":"a1", "std":"9", "year":"2017", "exam":"annual_P", "marks":[{"p":"45","m":"42","c":"18"}]}
{"name":"a2", "std":"9", "year":"2017", "exam":"halfyr_T", "marks":[{"p":"25","m":"30","c":"50"}]}
{"name":"a2", "std":"9", "year":"2017", "exam":"halfyr_P", "marks":[{"p":"41","m":"48","c":"28"}]}
{"name":"a2", "std":"9", "year":"2017", "exam":"annual_T", "marks":[{"p":"30","m":"48","c":"24"}]}
{"name":"a2", "std":"9", "year":"2017", "exam":"annual_P", "marks":[{"p":"35","m":"08","c":"38"}]}
{"name":"b1", "std":"10", "year":"2017", "exam":"halfyr_T","marks":[{"p":"45","m":"40","c":"50"}]}
{"name":"b1", "std":"10", "year":"2017", "exam":"halfyr_P", "marks": [{"p":"40","m":"28","c":"38"}]}
{"name":"b1", "std":"10", "year":"2017", "exam":"annual_T", "marks": [{"p":"40","m":"50","c":"48"}]}
{"name":"b1", "std":"10", "year":"2017", "exam":"annual_P", "marks": [{"p":"45","m":"42","c":"18"}]}
{"name":"b2", "std":"10", "year":"2017", "exam":"halfyr_T", "marks": [{"p":"25","m":"30","c":"50"}]}
{"name":"b2", "std":"10", "year":"2017", "exam":"halfyr_P", "marks": [{"p":"41","m":"48","c":"28"}]}
{"name":"b2", "std":"10", "year":"2017", "exam":"annual_T", "marks": [{"p":"30","m":"48","c":"24"}]}
{"name":"b2", "std":"10", "year":"2017", "exam":"annual_P", "marks": [{"p":"35","m":"08","c":"38"}]}