【发布时间】:2021-05-25 20:57:02
【问题描述】:
我正在构建一个简单的欢迎页面,其中包含姓名和年龄文本输入字段。我能够成功地限制名称字段上的字符输入计数,但是在年龄字段上使用相同的逻辑根本不起作用。想法?
class WelcomeViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var ageTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
nameTextField.delegate = self
ageTextField.delegate = self
}
// Character Count Code UITextField
func textField(_ nameTextField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
// get the current text, or use an empty string if that failed
let currentText = nameTextField.text ?? ""
// attempt to read the range they are trying to change, or exit if we can't
guard let stringRange = Range(range, in: currentText) else { return false }
// add their new text to the existing text
let updatedText = currentText.replacingCharacters(in: stringRange, with: string)
// make sure the result is under # characters
return updatedText.count <= 30
}
func textField2(_ ageTextField: UITextField, shouldChangeCharactersIn range2: NSRange, replacementString string2: String) -> Bool {
// get the current text, or use an empty string if that failed
let currentText2 = ageTextField.text ?? ""
// attempt to read the range they are trying to change, or exit if we can't
guard let stringRange2 = Range(range2, in: currentText2) else { return false }
// add their new text to the existing text
let updatedText2 = currentText2.replacingCharacters(in: stringRange2, with: string2)
// make sure the result is under # characters
return updatedText2.count <= 2
}
【问题讨论】: