2

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?

vacawama
  • 150,663
  • 30
  • 266
  • 294
  • Why does the question look like the same [question](http://stackoverflow.com/q/28121463/451475) asked just an hour ago? – zaph Jan 24 '15 at 02:54
  • Because I was answering that user's question and was about to post it when they were intimidated and deleted their question. – vacawama Jan 24 '15 at 02:55
  • In my opinion, their question was very clear. I'm sorry if you didn't think so, but I hate to see new users intimidated instead of gently guided. – vacawama Jan 24 '15 at 02:58
  • SO is about helping with code, an attempt should be made, that is how one learns. – zaph Jan 24 '15 at 03:01

1 Answers1

3

You can do this with the following four steps:

  1. Make your viewController a UITextFieldDelegate by adding that to the class definition.
  2. Add an IBOutlet to your textField by Control-dragging from the UITextField in your Storyboard to your code. Call it myTextField.
  3. In viewDidLoad(), set your viewController as the textField’s delegate.
  4. 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
        }
    }
    
vacawama
  • 150,663
  • 30
  • 266
  • 294
  • When I press backspace or delete then it doesn't work. Also if I clear textfield then it still keeps going from last point unless I reset tip to zero. – Apoorv Mote Jan 10 '16 at 19:00