首页 > 解决方案 > 如何检查文本字段在 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
}

我想知道是否还有其他方法可以实现此功能?我认为每当在文本字段上键入/删除一个字母时,上面的函数都会每次都被调用,所以我想知道是否有其他方法可以轻松地实现这些东西。

标签: iosswiftuitextfield

解决方案


 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
  }

推荐阅读