0

我添加了一个 UITextField,我想将其限制为仅字母和空格。因此,以下内容;

let set = CharacterSet (charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLKMNOPQRSTUVWXYZ")

如果可能的话,我怎么能在不使用委托的情况下做到这一点,如果可能的话,使用 RxSwift、RxCocoa 等方法。有没有人有一个绝妙的主意?

4

3 回答 3

1

你可以这样检查:

func validateField(enteredString:String) -> Bool {
    
    let validationFormat = "[a-zA-Z\\s]+"
    let fieldPredicate = NSPredicate(format:"SELF MATCHES %@", validationFormat)
    return fieldPredicate.evaluate(with: enteredString)
}

并使用

if !validateField(enteredString: textField.text ?? "") {
            
    print("Invalid String")
    return false
}
于 2020-08-25T05:17:43.097 回答
0

你可以在这里找到一个很好的 Rx 文本过滤实现: RxSwift 替换 shouldChangeCharactersInRange

在您的情况下,它应该如下所示:

textField.rx.text.orEmpty
    .map(alphaNumericAndWhitespace)
    .subscribe(onNext: setPreservingCursor(on: textField))
    .disposed(by: bag)

func alphaNumericAndWhitespace(_ text: String) -> String {
    let customSet = CharacterSet.alphanumerics.union(CharacterSet.whitespaces)
    return text.components(separatedBy: customSet.inverted).joined(separator: "")
}

func setPreservingCursor(on textField: UITextField) -> (_ newText: String) -> Void {
    return { newText in
        let cursorPosition = textField.offset(from: textField.beginningOfDocument, to: textField.selectedTextRange!.start) + newText.count - (textField.text?.count ?? 0)
        textField.text = newText
        if let newPosition = textField.position(from: textField.beginningOfDocument, offset: cursorPosition) {
            textField.selectedTextRange = textField.textRange(from: newPosition, to: newPosition)
        }
    }
}
于 2020-08-25T13:01:17.387 回答
0

您可以将事件添加到文本字段

textField1.addTarget(self, action: #selector(YourViewController.textFieldDidChange(_:)), forControlEvents: UIControlEvents.EditingChanged)

更改文本时处理文本

func textFieldDidChange(textField: UITextField) {
    // Check the textField text and update textField
}
于 2020-08-24T14:42:17.163 回答