I have a UITextField
(that represents a tip value) in my Storyboard that starts out as $0.00
. If the user types an 8
, I want the textFiel
You can do this with the following four steps:
UITextFieldDelegate
by adding that to the class
definition.IBOutlet
to your textField by Control-dragging from the UITextField
in your Storyboard to your code. Call it myTextField
.viewDidLoad()
, set your viewController as the textField’s delegate
.Implement textField:shouldChangeCharactersInRange:replacementString:
.
Take the incoming character and add it to the tip, and then use the String(format:)
constructor to format your string.
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var myTextField: UITextField!
// Tip value in cents
var tip: Int = 0
override func viewDidLoad() {
super.viewDidLoad()
myTextField.delegate = self
myTextField.text = "$0.00"
}
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
if let digit = Int(string) {
tip = tip * 10 + digit
textField.text = String(format:"$%d.%02d", tip/100, tip%100)
}
return false
}
}