How can I update the text values in the UITextfield in a reusable tableView cell, with different values in...





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







0















I am making a currency converter that updates currencies simultaneously as you type. The currencies are held in a tableView and the cell is a custom cell.



I want to be able to type into one cell, and see all the other cells update with the value from the conversion calculation. The calculation works, but I am not sure how to get the data back into the correct cells, as essentially there is only one as it is a reusable cell.



Here is the cell class, (I am just showing the input to keep things clear.):



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

}


Next I create the cells, I am showing more so that you get the idea of how I am setting the data for each cell to the selected currency.



Then I add a textFieldDidChange listener:



   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)


// here is the text listener



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

}


and here is where I do the calculation when it is typed, and get the results, it is not complete but I need to now somehow get these results shown inside the UITextfield for each cell, relating to the correct currency.



    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

}


Here basically I do the calculations based on which cell is being typed and I can find out which currency it is from the tag, and then using the index of the currency I can check my API and get its name and values, then I do the calculation to compare the other currencies to the value that the user entered. The calculations work and give the correct results, I just don't know how to send the results back into the correct cells. Thank you.



Sorry if it is very sloppy work I am still very new to coding.










share|improve this question





























    0















    I am making a currency converter that updates currencies simultaneously as you type. The currencies are held in a tableView and the cell is a custom cell.



    I want to be able to type into one cell, and see all the other cells update with the value from the conversion calculation. The calculation works, but I am not sure how to get the data back into the correct cells, as essentially there is only one as it is a reusable cell.



    Here is the cell class, (I am just showing the input to keep things clear.):



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

    }


    Next I create the cells, I am showing more so that you get the idea of how I am setting the data for each cell to the selected currency.



    Then I add a textFieldDidChange listener:



       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)


    // here is the text listener



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

    }


    and here is where I do the calculation when it is typed, and get the results, it is not complete but I need to now somehow get these results shown inside the UITextfield for each cell, relating to the correct currency.



        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

    }


    Here basically I do the calculations based on which cell is being typed and I can find out which currency it is from the tag, and then using the index of the currency I can check my API and get its name and values, then I do the calculation to compare the other currencies to the value that the user entered. The calculations work and give the correct results, I just don't know how to send the results back into the correct cells. Thank you.



    Sorry if it is very sloppy work I am still very new to coding.










    share|improve this question

























      0












      0








      0








      I am making a currency converter that updates currencies simultaneously as you type. The currencies are held in a tableView and the cell is a custom cell.



      I want to be able to type into one cell, and see all the other cells update with the value from the conversion calculation. The calculation works, but I am not sure how to get the data back into the correct cells, as essentially there is only one as it is a reusable cell.



      Here is the cell class, (I am just showing the input to keep things clear.):



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

      }


      Next I create the cells, I am showing more so that you get the idea of how I am setting the data for each cell to the selected currency.



      Then I add a textFieldDidChange listener:



         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)


      // here is the text listener



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

      }


      and here is where I do the calculation when it is typed, and get the results, it is not complete but I need to now somehow get these results shown inside the UITextfield for each cell, relating to the correct currency.



          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

      }


      Here basically I do the calculations based on which cell is being typed and I can find out which currency it is from the tag, and then using the index of the currency I can check my API and get its name and values, then I do the calculation to compare the other currencies to the value that the user entered. The calculations work and give the correct results, I just don't know how to send the results back into the correct cells. Thank you.



      Sorry if it is very sloppy work I am still very new to coding.










      share|improve this question














      I am making a currency converter that updates currencies simultaneously as you type. The currencies are held in a tableView and the cell is a custom cell.



      I want to be able to type into one cell, and see all the other cells update with the value from the conversion calculation. The calculation works, but I am not sure how to get the data back into the correct cells, as essentially there is only one as it is a reusable cell.



      Here is the cell class, (I am just showing the input to keep things clear.):



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

      }


      Next I create the cells, I am showing more so that you get the idea of how I am setting the data for each cell to the selected currency.



      Then I add a textFieldDidChange listener:



         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)


      // here is the text listener



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

      }


      and here is where I do the calculation when it is typed, and get the results, it is not complete but I need to now somehow get these results shown inside the UITextfield for each cell, relating to the correct currency.



          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

      }


      Here basically I do the calculations based on which cell is being typed and I can find out which currency it is from the tag, and then using the index of the currency I can check my API and get its name and values, then I do the calculation to compare the other currencies to the value that the user entered. The calculations work and give the correct results, I just don't know how to send the results back into the correct cells. Thank you.



      Sorry if it is very sloppy work I am still very new to coding.







      ios swift uitableview uitextfield






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Jan 4 at 0:22









      Peter RuppertPeter Ruppert

      392114




      392114
























          1 Answer
          1






          active

          oldest

          votes


















          1














          You can put your results in a dictionary type [Int : Double] where Int is the coinIndex, and Double part is the answer from the conversion. Then, after your calculations finish, you can call tableView.reloadData.().



          You also need to make modifications to your cellForRowAt to show the conversion.



          Try this:



          In your UIViewController, declare



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


          Then in 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")
          }


          You need to update the conversions in your calculation function



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


          I think you can improve your calculations function. You can iterate on the coin index instead of updating the answers recursively. Good luck!






          share|improve this answer


























          • This is looking great! thank you! For the part in cellForRowAt, I can't do that until I've entered something into a text box or it finds nil, but that may also be because I've changed it to let conversion = conversions[index] cell.cellCalcInput.text = String(Double(conversion!)) and force unwrapped as with your original code I got an error: 'Cannot invoke initializer for type 'String' with an argument list of type '(Double?)'' Any Ideas?

            – Peter Ruppert
            Jan 4 at 12:05













          • I can probably just use a Boolean that sets true from textDidChange to check if that is True before doing cell.cellCalcInput.text = String(conversion) So it is only called if there is definitely a value in the textInput. Will check this when I can and accept when I have it all working!

            – Peter Ruppert
            Jan 4 at 20:16











          • I updated the answer. You can use the ?? operator to check if a value is nil, and if it is, pass an alternative value. For the case of String(Double(conversion!)), keep in mind that the Double(String) constructor will return an optional, because not all strings are convertible to double.

            – ocsahan
            Jan 4 at 20:43











          • Thank you, got that working. When you say I can improve my calculations function can you possibly elaborate on that? The final problem I am having is handling all the indexes and the calculation before adding them to conversions dictionary. I am trying to get a dictionary of the indexes and the original price, and then perform the calculation on each item in that dict, and putting that answer back into the conversions dictionary, but I am unsure how to format this. Thank you.

            – Peter Ruppert
            Jan 5 at 22:04











          • That would indeed be a neater solution. Keep in mind you can iterate through each key-value pair in the dictionary using a for loop. So your comparator will be the key in the dictionary, and you will use dataIndex to calculate the rates. This way, you can put all calculation logic in the for loop and do away with the recursion!

            – ocsahan
            Jan 6 at 19:00












          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54031625%2fhow-can-i-update-the-text-values-in-the-uitextfield-in-a-reusable-tableview-cell%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          1














          You can put your results in a dictionary type [Int : Double] where Int is the coinIndex, and Double part is the answer from the conversion. Then, after your calculations finish, you can call tableView.reloadData.().



          You also need to make modifications to your cellForRowAt to show the conversion.



          Try this:



          In your UIViewController, declare



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


          Then in 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")
          }


          You need to update the conversions in your calculation function



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


          I think you can improve your calculations function. You can iterate on the coin index instead of updating the answers recursively. Good luck!






          share|improve this answer


























          • This is looking great! thank you! For the part in cellForRowAt, I can't do that until I've entered something into a text box or it finds nil, but that may also be because I've changed it to let conversion = conversions[index] cell.cellCalcInput.text = String(Double(conversion!)) and force unwrapped as with your original code I got an error: 'Cannot invoke initializer for type 'String' with an argument list of type '(Double?)'' Any Ideas?

            – Peter Ruppert
            Jan 4 at 12:05













          • I can probably just use a Boolean that sets true from textDidChange to check if that is True before doing cell.cellCalcInput.text = String(conversion) So it is only called if there is definitely a value in the textInput. Will check this when I can and accept when I have it all working!

            – Peter Ruppert
            Jan 4 at 20:16











          • I updated the answer. You can use the ?? operator to check if a value is nil, and if it is, pass an alternative value. For the case of String(Double(conversion!)), keep in mind that the Double(String) constructor will return an optional, because not all strings are convertible to double.

            – ocsahan
            Jan 4 at 20:43











          • Thank you, got that working. When you say I can improve my calculations function can you possibly elaborate on that? The final problem I am having is handling all the indexes and the calculation before adding them to conversions dictionary. I am trying to get a dictionary of the indexes and the original price, and then perform the calculation on each item in that dict, and putting that answer back into the conversions dictionary, but I am unsure how to format this. Thank you.

            – Peter Ruppert
            Jan 5 at 22:04











          • That would indeed be a neater solution. Keep in mind you can iterate through each key-value pair in the dictionary using a for loop. So your comparator will be the key in the dictionary, and you will use dataIndex to calculate the rates. This way, you can put all calculation logic in the for loop and do away with the recursion!

            – ocsahan
            Jan 6 at 19:00
















          1














          You can put your results in a dictionary type [Int : Double] where Int is the coinIndex, and Double part is the answer from the conversion. Then, after your calculations finish, you can call tableView.reloadData.().



          You also need to make modifications to your cellForRowAt to show the conversion.



          Try this:



          In your UIViewController, declare



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


          Then in 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")
          }


          You need to update the conversions in your calculation function



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


          I think you can improve your calculations function. You can iterate on the coin index instead of updating the answers recursively. Good luck!






          share|improve this answer


























          • This is looking great! thank you! For the part in cellForRowAt, I can't do that until I've entered something into a text box or it finds nil, but that may also be because I've changed it to let conversion = conversions[index] cell.cellCalcInput.text = String(Double(conversion!)) and force unwrapped as with your original code I got an error: 'Cannot invoke initializer for type 'String' with an argument list of type '(Double?)'' Any Ideas?

            – Peter Ruppert
            Jan 4 at 12:05













          • I can probably just use a Boolean that sets true from textDidChange to check if that is True before doing cell.cellCalcInput.text = String(conversion) So it is only called if there is definitely a value in the textInput. Will check this when I can and accept when I have it all working!

            – Peter Ruppert
            Jan 4 at 20:16











          • I updated the answer. You can use the ?? operator to check if a value is nil, and if it is, pass an alternative value. For the case of String(Double(conversion!)), keep in mind that the Double(String) constructor will return an optional, because not all strings are convertible to double.

            – ocsahan
            Jan 4 at 20:43











          • Thank you, got that working. When you say I can improve my calculations function can you possibly elaborate on that? The final problem I am having is handling all the indexes and the calculation before adding them to conversions dictionary. I am trying to get a dictionary of the indexes and the original price, and then perform the calculation on each item in that dict, and putting that answer back into the conversions dictionary, but I am unsure how to format this. Thank you.

            – Peter Ruppert
            Jan 5 at 22:04











          • That would indeed be a neater solution. Keep in mind you can iterate through each key-value pair in the dictionary using a for loop. So your comparator will be the key in the dictionary, and you will use dataIndex to calculate the rates. This way, you can put all calculation logic in the for loop and do away with the recursion!

            – ocsahan
            Jan 6 at 19:00














          1












          1








          1







          You can put your results in a dictionary type [Int : Double] where Int is the coinIndex, and Double part is the answer from the conversion. Then, after your calculations finish, you can call tableView.reloadData.().



          You also need to make modifications to your cellForRowAt to show the conversion.



          Try this:



          In your UIViewController, declare



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


          Then in 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")
          }


          You need to update the conversions in your calculation function



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


          I think you can improve your calculations function. You can iterate on the coin index instead of updating the answers recursively. Good luck!






          share|improve this answer















          You can put your results in a dictionary type [Int : Double] where Int is the coinIndex, and Double part is the answer from the conversion. Then, after your calculations finish, you can call tableView.reloadData.().



          You also need to make modifications to your cellForRowAt to show the conversion.



          Try this:



          In your UIViewController, declare



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


          Then in 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")
          }


          You need to update the conversions in your calculation function



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


          I think you can improve your calculations function. You can iterate on the coin index instead of updating the answers recursively. Good luck!







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Jan 4 at 20:38

























          answered Jan 4 at 3:43









          ocsahanocsahan

          765




          765













          • This is looking great! thank you! For the part in cellForRowAt, I can't do that until I've entered something into a text box or it finds nil, but that may also be because I've changed it to let conversion = conversions[index] cell.cellCalcInput.text = String(Double(conversion!)) and force unwrapped as with your original code I got an error: 'Cannot invoke initializer for type 'String' with an argument list of type '(Double?)'' Any Ideas?

            – Peter Ruppert
            Jan 4 at 12:05













          • I can probably just use a Boolean that sets true from textDidChange to check if that is True before doing cell.cellCalcInput.text = String(conversion) So it is only called if there is definitely a value in the textInput. Will check this when I can and accept when I have it all working!

            – Peter Ruppert
            Jan 4 at 20:16











          • I updated the answer. You can use the ?? operator to check if a value is nil, and if it is, pass an alternative value. For the case of String(Double(conversion!)), keep in mind that the Double(String) constructor will return an optional, because not all strings are convertible to double.

            – ocsahan
            Jan 4 at 20:43











          • Thank you, got that working. When you say I can improve my calculations function can you possibly elaborate on that? The final problem I am having is handling all the indexes and the calculation before adding them to conversions dictionary. I am trying to get a dictionary of the indexes and the original price, and then perform the calculation on each item in that dict, and putting that answer back into the conversions dictionary, but I am unsure how to format this. Thank you.

            – Peter Ruppert
            Jan 5 at 22:04











          • That would indeed be a neater solution. Keep in mind you can iterate through each key-value pair in the dictionary using a for loop. So your comparator will be the key in the dictionary, and you will use dataIndex to calculate the rates. This way, you can put all calculation logic in the for loop and do away with the recursion!

            – ocsahan
            Jan 6 at 19:00



















          • This is looking great! thank you! For the part in cellForRowAt, I can't do that until I've entered something into a text box or it finds nil, but that may also be because I've changed it to let conversion = conversions[index] cell.cellCalcInput.text = String(Double(conversion!)) and force unwrapped as with your original code I got an error: 'Cannot invoke initializer for type 'String' with an argument list of type '(Double?)'' Any Ideas?

            – Peter Ruppert
            Jan 4 at 12:05













          • I can probably just use a Boolean that sets true from textDidChange to check if that is True before doing cell.cellCalcInput.text = String(conversion) So it is only called if there is definitely a value in the textInput. Will check this when I can and accept when I have it all working!

            – Peter Ruppert
            Jan 4 at 20:16











          • I updated the answer. You can use the ?? operator to check if a value is nil, and if it is, pass an alternative value. For the case of String(Double(conversion!)), keep in mind that the Double(String) constructor will return an optional, because not all strings are convertible to double.

            – ocsahan
            Jan 4 at 20:43











          • Thank you, got that working. When you say I can improve my calculations function can you possibly elaborate on that? The final problem I am having is handling all the indexes and the calculation before adding them to conversions dictionary. I am trying to get a dictionary of the indexes and the original price, and then perform the calculation on each item in that dict, and putting that answer back into the conversions dictionary, but I am unsure how to format this. Thank you.

            – Peter Ruppert
            Jan 5 at 22:04











          • That would indeed be a neater solution. Keep in mind you can iterate through each key-value pair in the dictionary using a for loop. So your comparator will be the key in the dictionary, and you will use dataIndex to calculate the rates. This way, you can put all calculation logic in the for loop and do away with the recursion!

            – ocsahan
            Jan 6 at 19:00

















          This is looking great! thank you! For the part in cellForRowAt, I can't do that until I've entered something into a text box or it finds nil, but that may also be because I've changed it to let conversion = conversions[index] cell.cellCalcInput.text = String(Double(conversion!)) and force unwrapped as with your original code I got an error: 'Cannot invoke initializer for type 'String' with an argument list of type '(Double?)'' Any Ideas?

          – Peter Ruppert
          Jan 4 at 12:05







          This is looking great! thank you! For the part in cellForRowAt, I can't do that until I've entered something into a text box or it finds nil, but that may also be because I've changed it to let conversion = conversions[index] cell.cellCalcInput.text = String(Double(conversion!)) and force unwrapped as with your original code I got an error: 'Cannot invoke initializer for type 'String' with an argument list of type '(Double?)'' Any Ideas?

          – Peter Ruppert
          Jan 4 at 12:05















          I can probably just use a Boolean that sets true from textDidChange to check if that is True before doing cell.cellCalcInput.text = String(conversion) So it is only called if there is definitely a value in the textInput. Will check this when I can and accept when I have it all working!

          – Peter Ruppert
          Jan 4 at 20:16





          I can probably just use a Boolean that sets true from textDidChange to check if that is True before doing cell.cellCalcInput.text = String(conversion) So it is only called if there is definitely a value in the textInput. Will check this when I can and accept when I have it all working!

          – Peter Ruppert
          Jan 4 at 20:16













          I updated the answer. You can use the ?? operator to check if a value is nil, and if it is, pass an alternative value. For the case of String(Double(conversion!)), keep in mind that the Double(String) constructor will return an optional, because not all strings are convertible to double.

          – ocsahan
          Jan 4 at 20:43





          I updated the answer. You can use the ?? operator to check if a value is nil, and if it is, pass an alternative value. For the case of String(Double(conversion!)), keep in mind that the Double(String) constructor will return an optional, because not all strings are convertible to double.

          – ocsahan
          Jan 4 at 20:43













          Thank you, got that working. When you say I can improve my calculations function can you possibly elaborate on that? The final problem I am having is handling all the indexes and the calculation before adding them to conversions dictionary. I am trying to get a dictionary of the indexes and the original price, and then perform the calculation on each item in that dict, and putting that answer back into the conversions dictionary, but I am unsure how to format this. Thank you.

          – Peter Ruppert
          Jan 5 at 22:04





          Thank you, got that working. When you say I can improve my calculations function can you possibly elaborate on that? The final problem I am having is handling all the indexes and the calculation before adding them to conversions dictionary. I am trying to get a dictionary of the indexes and the original price, and then perform the calculation on each item in that dict, and putting that answer back into the conversions dictionary, but I am unsure how to format this. Thank you.

          – Peter Ruppert
          Jan 5 at 22:04













          That would indeed be a neater solution. Keep in mind you can iterate through each key-value pair in the dictionary using a for loop. So your comparator will be the key in the dictionary, and you will use dataIndex to calculate the rates. This way, you can put all calculation logic in the for loop and do away with the recursion!

          – ocsahan
          Jan 6 at 19:00





          That would indeed be a neater solution. Keep in mind you can iterate through each key-value pair in the dictionary using a for loop. So your comparator will be the key in the dictionary, and you will use dataIndex to calculate the rates. This way, you can put all calculation logic in the for loop and do away with the recursion!

          – ocsahan
          Jan 6 at 19:00




















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54031625%2fhow-can-i-update-the-text-values-in-the-uitextfield-in-a-reusable-tableview-cell%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Monofisismo

          Angular Downloading a file using contenturl with Basic Authentication

          Olmecas