首页 > 解决方案 > 如何更新可重用 tableView 单元格中 UITextfield 中的文本值,每个单元格中的值不同

问题描述

我正在制作一个货币转换器,可以在您输入时同时更新货币。货币保存在 tableView 中,单元格是自定义单元格。

我希望能够在一个单元格中输入内容,并查看所有其他单元格都使用转换计算中的值进行更新。计算有效,但我不确定如何将数据恢复到正确的单元格中,因为本质上只有一个单元格,因为它是可重复使用的单元格。

这是单元格类,(我只是显示输入以保持清晰。):

class PageCell: UITableViewCell {

let cellCalcInput = UITextField()

func configureCustomCell() {

    contentView.addSubview(cellCalcInput)
    cellCalcInput.translatesAutoresizingMaskIntoConstraints = false
    cellCalcInput.rightAnchor.constraint(equalTo: contentView.rightAnchor, constant: -10).isActive = true
    cellCalcInput.centerYAnchor.constraint(equalTo: contentView.centerYAnchor).isActive = true
    cellCalcInput.font = secondFont?.withSize(18)
    cellCalcInput.textColor = .white
    cellCalcInput.placeholder = "Enter an amount"
    cellCalcInput.keyboardType = .decimalPad
    cellCalcInput.borderStyle = .roundedRect
    cellCalcInput.backgroundColor = .clear

    cellCalcInput.isHidden = true
    self.backgroundColor = .darkGray
    contentView.contentMode = .scaleAspectFit

}

override init(style: UITableViewCell.CellStyle, reuseIdentifier: String!) {
    super.init(style: style, reuseIdentifier: reuseIdentifier)
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

}

接下来我创建单元格,我将展示更多内容,以便您了解我如何将每个单元格的数据设置为所选货币。

然后我添加一个 textFieldDidChange 监听器:

   override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    var coinName = String()
    tableView.separatorStyle = .none

    let cell:PageCell = tableView.dequeueReusableCell(withIdentifier: "PageCell") as! PageCell
    cell.configureCustomCell()
    let index = indexPath.row
    let coins = Manager.shared.coins
    let coin = coins[index]
    var coinIndex = Int()
    coinIndex = CGPrices.shared.coinData.index(where: { $0.id == coin })!
    let unit = CGExchange.shared.exchangeData[0].rates[defaultCurrency]!.unit
    coinIndexes.append(coinIndex)

    //Prices from btc Exchange rate.
    let btcPrice = CGPrices.shared.coinData[coinIndex].current_price!
    let dcExchangeRate = CGExchange.shared.exchangeData[0].rates[defaultCurrency]!.value
    let realPrice = (btcPrice*dcExchangeRate)

    setBackground(dataIndex: coinIndex, contentView: cell.contentView)

    coinName = CGPrices.shared.coinData[coinIndex].name

    let imageString = CGPrices.shared.coinData[coinIndex].image 
    cell.theImageView.sd_setImage(with: URL(string: imageString), placeholderImage: UIImage(named: "CryptiXJustX"))

    cell.cellTextLabel.text = coinName
    cell.cellDetailLabel.text = "\(unit)\((round(1000*realPrice)/1000))"

    cell.cellCalcInput.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)

// 这里是文本监听器

    return cell
}

@objc func textFieldDidChange(_ textField: UITextField) {

    var index = Int()
    index = textField.tag

    if textField.text != "" {
    calculations(dataIndex: index, calcInput: textField)
    } else {
        print("no text")
    }

}

这是我在输入时进行计算并获得结果的地方,它不完整,但我现在需要以某种方式在每个单元格的 UITextfield 中显示这些结果,与正确的货币有关。

    var coinIndexes = [Int]()
var answers = [Double]()
//
var comparitorIndex = 0
func calculations(dataIndex: Int, calcInput: UITextField) {
    let exchangeRate = CGExchange.shared.exchangeData[0].rates[defaultCurrency]!.value
//
    let btcPrice = CGPrices.shared.coinData[dataIndex].current_price!

//
    if answers.count < coinIndexes.count {

        var calculation = ""
        if CGPrices.shared.coinData[dataIndex].id == "bitcoin" {
            calculation = String(Double(calcInput.text!)! / btcPrice)
        } else {
        calculation = String(Double(calcInput.text!)! * btcPrice)
        }
        let calcAsDouble = Double(calculation)
        let calcFinal = Double(round(1000*calcAsDouble!)/1000)

        var comparitor = coinIndexes[comparitorIndex]
        var comparitorPrice = CGPrices.shared.coinData[comparitor].current_price!

        var comparitorAnswer = (calcFinal/comparitorPrice)
        answers.append(comparitorAnswer)

        comparitorIndex += 1
        print(comparitorAnswer)
        calculations(dataIndex: dataIndex, calcInput: calcInput)
    }
    comparitorIndex = 0

}

这里基本上我根据输入的单元格进行计算,我可以从标签中找出它是哪种货币,然后使用货币的索引我可以检查我的 API 并获取它的名称和值,然后我做计算以将其他货币与用户输入的值进行比较。计算工作并给出正确的结果,我只是不知道如何将结果发送回正确的单元格。谢谢你。

抱歉,如果这是非常草率的工作,我对编码还是很陌生。

标签: iosswiftuitableviewuitextfield

解决方案


您可以将结果放入字典类型中[Int : Double],其中,部分是转换的答案。然后,在您的计算完成后,您可以调用.IntcoinIndexDoubletableView.reloadData.()

您还需要对您的进行修改以cellForRowAt显示转换。

尝试这个:

在你的 UIViewController 中,声明

var conversions: [Int : Double] = [:]

然后在cellForRowAt

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    // your code here
    let conversion = conversions[index]
    // the ?? operator will pass "No Value" string if conversion is nil.
    cell.cellCalcInput.text = String(conversion ?? "No Value")
}

您需要更新计算函数中的转换

func calculations(dataIndex: Int, calcInput: UITextField) {
    // your code here
    conversions[comparatorIndex] = comparatorAnswer
    // once all conversions are entered
    tableView.reloadData()
}

我认为你可以改进你的calculations功能。您可以迭代硬币索引,而不是递归地更新答案。祝你好运!


推荐阅读