ios - 如何检查文本字段在 Swift 中是否有多个字母?
问题描述
我正在处理 Swift 中的文本字段,我将要实现的是禁用导航按钮,除非文本字段中有 0 个字符,如果文本字段中有超过 1 个字母,则在文本字段上添加删除按钮文本字段,如 iOS 默认日历应用程序。
当标题文本字段中没有字母时,条形按钮项“添加”被禁用。
当标题文本字段中有 1+ 个字母时,启用“添加”按钮并显示删除按钮。
我查看了文本字段委托方法,我想我可以通过使用 shouldChangeCharactersIn 方法(?)
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
// check if there is a letter in the text field
// if there is, enable the Add button and show delete icon
// if there is not, disable the add button and hide the delete icon
return true
}
我想知道是否还有其他方法可以实现此功能?我认为每当在文本字段上键入/删除一个字母时,上面的函数都会每次都被调用,所以我想知道是否有其他方法可以轻松地实现这些东西。
解决方案
func textFieldDidChangeSelection(_ textField: UITextField) {
validateTextField(text:textField.tex)
}
您的方法 shouldChangeCharactersIn 有时无法正常工作,因此可以使用此方法创建一个获取文本并禁用和启用导航栏和删除按钮的功能,例如
func validateTextField(text:String) {
if text.count > 1 {
textField.clearButtonMode = .whileEditing
} else if text.count <= 1 {
textField.clearButtonMode = .never
} else if text.count < 1 {
navigationItem.leftBarButtonItem.tintColor = .lightGray
}
推荐阅读
- android - 不能在意图中同时传递多个整数
- javascript - 对 ![String instance] 返回 true 的字符串调用 String.replace?
- python - Speech to Text - 将演讲者标签映射到 JSON 响应中的相应成绩单
- php - AMP:使用查询字符串参数“?amp=1”或子文件夹“/amp”有什么不同吗?
- angular - 如何在 Angular 6 中访问 http 响应标头
- python - 总和为常数的加权随机数数组
- android - 使用google api客户端编辑方法python上传扩展文件
- facebook - Facebook App Tester - 他们必须是开发人员吗?
- c++ - 这是绑定到要变异的非 RVO 返回值的惯用方式吗?
- haskell - Foldable中foldr实现的解释