【问题标题】:How to check if textfield has more than one letter in Swift?如何检查文本字段在 Swift 中是否有多个字母?
【发布时间】:2021-12-02 12:01:29
【问题描述】:

我正在处理 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
}

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

【问题讨论】:

  • 您要检查单个文本字段还是多个文本字段是否有单个字符?

标签: ios swift uitextfield


【解决方案1】:
 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
  }

【讨论】:

    【解决方案2】:

    您可以使用情节提要方法来计算特定文本字段的文本计数。

    1.Ctrl + Click on the textfield in interface builder.
    
    1. 从 EditingChanged 拖动到助手视图中的视图控制器类内部。

    3.命名您的函数(例如“textFieldEditingChanged”)并单击连接。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-04
      • 2011-05-26
      • 2021-03-06
      • 1970-01-01
      • 2015-07-10
      • 2014-02-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多