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 textField to read $0.08. If the user then types a 3, I want the textField to read $0.83. If the user then types 5, I want the textField to read $8.35. How would I go about changing the input to a UITextField in this manner?
You can do this with the following four steps:
- Make your viewController a
UITextFieldDelegateby adding that to theclassdefinition. - Add an
IBOutletto your textField by Control-dragging from theUITextFieldin your Storyboard to your code. Call itmyTextField. - In
viewDidLoad(), set your viewController as the textField’sdelegate. Implement
textField:shouldChangeCharactersInRange:replacementString:. Take the incoming character and add it to the tip, and then use theString(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 } }
来源:https://stackoverflow.com/questions/28121800/how-to-customize-numeric-input-for-a-uitextfield