How to customize numeric input for a UITextField?

前端 未结 1 1473
孤街浪徒
孤街浪徒 2021-01-22 11:34

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

1条回答
  •  礼貌的吻别
    2021-01-22 12:07

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

    0 讨论(0)
提交回复
热议问题