ios - 字符数在第二个文本字段上不起作用
问题描述
我正在构建一个简单的欢迎页面,其中包含一个姓名和年龄文本输入字段。我能够成功地限制名称字段上的字符输入计数,但在年龄字段上使用相同的逻辑根本不起作用。想法?
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
}
解决方案
textField(_:shouldChangeCharactersIn:replacementString:)
委托方法具有系统调用的特定签名 ( )。您的第一个函数使用该模式。
您的第二个目前没有,因为您已经命名了它textField2
- 系统没有理由知道调用以该前缀开头的东西。
相反,您可能应该使用单个函数,然后根据UITextField
发送到第一个参数的函数使其行为不同:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if textField == nameTextField {
//content
}
if textField == ageTextField {
//content
}
}
这显然可能是一个else if
,或者甚至只是一个,else
如果你限制在 2 个文本字段。在if
块中,您可以调用单独的专用函数,或者将所有逻辑保留在if
块中。
示例switch
:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
switch textfield {
case nameTextField:
//content
case ageTextField:
//content
default:
return true
}
}
推荐阅读
- python - 将球体拟合到 3D 点
- html - 如何通过其元素从网站中删除空格
- tensorflow - 如何在 lstm 输出的每个时间步应用平均池化?
- python-3.x - 将列表作为参数传递给类
- python - 尝试终止任务管理器时访问被拒绝
- python - Scrapy 和 ASPX 网站 - 无法拉出超过 11 - 302 错误的页面
- c++ - 您可以将 nullptr 与其他指针进行比较以进行排序吗?它总是更小吗?
- java - 在 Where 子句中使用 JSON 值更新查询
- javascript - 使用 RegExp 和 eval() 替换值
- python - 将json存储为可搜索的python对象?