如何自定义UITextField的数字输入? [英] How to customize numeric input for a UITextField?
问题描述
我的Storyboard中有一个 UITextField
(代表小费值),以 $ 0.00
开头。如果用户键入 8
,我希望textField读取 $ 0.08
。如果用户然后键入 3
,我希望textField读取 $ 0.83
。如果用户然后键入 5
,我希望textField读取 $ 8.35
。如何以这种方式将输入更改为 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?
推荐答案
您可以通过以下四个步骤执行此操作:
You can do this with the following four steps:
- 使您的viewController成为
UITextFieldDelegate
将其添加到类
定义。 - 添加
IBOutlet
通过 Control 将textField从您的Storyboard中的UITextField
拖放到您的代码中。称之为myTextField
。 - 在
viewDidLoad()
中,将viewController设置为textField的委托
。 -
实现
textField:shouldChangeCharactersInRange:replacementString:
。
获取传入的字符并将其添加到提示,然后使用String(format:)
构造函数来格式化字符串。
- Make your viewController a
UITextFieldDelegate
by adding that to theclass
definition. - Add an
IBOutlet
to your textField by Control-dragging from theUITextField
in 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
}
}
这篇关于如何自定义UITextField的数字输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!