How to customize numeric input for a UITextField?

大憨熊 提交于 2019-12-02 00:48:20

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
        }
    }
    
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!