Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
751 views
in Technique[技术] by (71.8m points)

ios - How to customize numeric input for a UITextField?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
        }
    }
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...