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.
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!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.