New to swift, I built a simple app with a texfield, a button and a label. I want to be able to enter a number into the textfield and have it dynamically change to a currency, i.e. 1200 changes to $1,200.00. Then when I push my button I want to have that currency multiply with a constant say 2 and display the currency amount in the label as it did in the textfield. I can't seem to get this currency converter to work in Swift 3. My code is pretty simplistic so I have not really showed anything here just looking for a way to format the textfield and label answer.
import UIKit
class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource, UITextFieldDelegate {
@IBOutlet var Picker1: UIPickerView!
var Array = ["1", "2"]
@IBOutlet var grossSalary: UITextField!
@IBOutlet var text: UILabel!
var mult = 2
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
Picker1.delegate = self
Picker1.dataSource = self
grossSalary.delegate = self
grossSalary.keyboardType = UIKeyboardType.numbersAndPunctuation
text.text = ""
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return Array[row]
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return Array.count
}
func numberOfComponents(in pickerView: UIPickerView) -> Int{
return 1
}
@objc(textField:shouldChangeCharactersInRange:replacementString:) func textField(_ grossSalary: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let invalidCharacters = CharacterSet(charactersIn: "0123456789.").inverted
return string.rangeOfCharacter(from: invalidCharacters, options: [], range: string.startIndex ..< string.endIndex) == nil
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
grossSalary.resignFirstResponder()
return true
}
@IBAction func changetext(_ sender: AnyObject) {
text.text = grossSalary.text
// let result = (text.text.toInt() ?? 0) * 2
// text.text = "\(result)"
let a = grossSalary.text
let b = Int(a!)! * mult
text.text = ("$\(b)0")
}
}