【问题标题】:Restrict UITextField from entering 0 as first character without using UITextField delegate限制 UITextField 在不使用 UITextField 委托的情况下输入 0 作为第一个字符
【发布时间】:2021-12-23 22:53:07
【问题描述】:

我正在尝试通过向 textField 对象(如 myTextField.editingChanged)提供操作来实现此功能

我知道这可以通过使用 textField 的委托方法轻松完成

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    if string == "0" {
       if textField.text!.count == 0 {
          return false
        }
       return true
    }
}

但我需要在自定义方法中执行此操作并将其作为目标添加到 textField。肯定有什么办法。

【问题讨论】:

  • “但我需要在自定义方法中执行此操作,并将其作为目标添加到 textField。” 为什么?您需要解释是什么阻碍了您简单地实现委托方法,否则将很难为最明显和最正确的解决方案找到替代解决方案。

标签: ios swift uitextfield


【解决方案1】:

您可以在文本字段上添加观察者,例如

NotificationCenter.default.addObserver(self, selector: #selector(textFieldDidChangeText), name: UITextField.textDidChangeNotification, object: nil)

并在下面的函数中给出您的自定义实现

@objc func textFieldDidChangeText(_ textField: UITextField) { ... }

不要忘记删除观察者。

【讨论】:

  • 引用苹果文档“如果您的应用程序针对 iOS 9.0 及更高版本或 macOS 10.11 及更高版本,并且您使用了 addObserver(_:selector:name:object:),则无需取消注册观察者。 "所以你的最后一句话“不要忘记删除观察者”。不太正确:)
  • @SandeepBhandari remove 观察者对于特定观察者不是必需的,而不是所有类型的观察者。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多