You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift中TableViewCell内TextField取值存入DataModel的问题求助

问题解决方案

一、解决「未收起键盘时无法保存TextField值」的问题

有两种实用方案可选:

方案1:监听TextField编辑变化,实时更新数据

给TextField绑定editingChanged事件,用户每输入一个字符都会触发数据更新,无需等待收起键盘:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "PriceTableViewCell", for: indexPath) as! PriceTableViewCell
    let obj = self.countryArray[indexPath.row]
    cell.editPriceCodeLabel.text = obj.iso_code ?? ""
    cell.editPriceTextField.tag = indexPath.row
    cell.editPriceTextField.delegate = self
    
    // 先移除旧监听,避免cell复用重复绑定
    cell.editPriceTextField.removeTarget(nil, action: nil, for: .editingChanged)
    // 添加编辑变化监听
    cell.editPriceTextField.addTarget(self, action: #selector(textFieldEditingChanged(_:)), for: .editingChanged)
    
    // 恢复之前保存的输入值
    if let value = self.textFieldValues[indexPath] {
        cell.editPriceTextField.text = value
    }
    
    cell.selectionStyle = .none
    return cell
}

// 实现监听方法
@objc private func textFieldEditingChanged(_ textField: UITextField) {
    let indexPath = IndexPath(row: textField.tag, section: 0)
    self.textFieldValues[indexPath] = textField.text ?? ""
    // 无需刷新cell,TextField已实时显示最新内容
}

方案2:在保存时直接遍历TableView获取所有最新值

如果只需要在用户点击保存时拿到所有输入值,这种方式更简洁,避免频繁更新数据:

// 示例:保存按钮点击事件
@objc private func saveButtonTapped() {
    var finalPriceArray = [PriceModel]()
    for row in 0..<countryArray.count {
        let indexPath = IndexPath(row: row, section: 0)
        if let cell = retailPriceTableView.cellForRow(at: indexPath) as? PriceTableViewCell {
            let inputPrice = cell.editPriceTextField.text ?? ""
            let country = countryArray[row]
            let model = PriceModel(country: country, price: inputPrice, cancel: true)
            finalPriceArray.append(model)
        }
    }
    // 回调传递最终数据
    onSaveClick?(finalPriceArray)
}

二、修正现有代码的其他问题

  1. 移除cellForRowAt中添加priceArray的逻辑:
    原代码每次cell复用都会往priceArray中追加元素,导致数组出现重复数据。应该在需要生成最终数据时(比如保存操作)统一处理,参考方案2的逻辑。

  2. 优化textFieldDidEndEditing逻辑:
    不需要刷新当前行,否则会导致光标位置丢失:

    extension PriceScreen: UITextFieldDelegate {
        func textFieldDidEndEditing(_ textField: UITextField) {
            let indexPath = IndexPath(row: textField.tag, section: 0)
            self.textFieldValues[indexPath] = textField.text ?? ""
            // 移除reloadRows的调用
        }
    }
    

内容的提问来源于stack exchange,提问作者SwiftNewbie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 13:06:03