gpt4 book ai didi

swift - 如何使用 RxSwift 观察 UITextField 中的输入变化?

转载 作者:行者123 更新时间:2023-11-28 07:23:07 26 4
gpt4 key购买 nike

我正在尝试验证文本并将其与 UITextField 键入事件合并。这是验证序列:

let validation = textField.rx.text.map {ValidationService.validate($0)}

我测试了所有组合方法但没有结果:

Observable.zip(textField.rx.controlEvent(.editingChanged), validation)

// Select
// No event

// Typing: "A"
// zip failed(message: "Field cannot be empty") () <- wrong

// Typing: "Aa"
// zip failed(message: "Field cannot be empty") () <- wrong

// Typing: "Aaa"
// zip failed(message: "Email is wrong") () <- correct

// UnSelect
// No event

Observable.combineLatest(textField.rx.controlEvent(.editingChanged), validation)

// Select
// No event

// Typing: "A"
// combineLatest combineLatest failed(message: "Email is wrong") () <- correct

// Typing: "Aa"
// combineLatest failed(message: "Field cannot be empty") () <- correct
// combineLatest failed(message: "Field cannot be empty") () <- correct

// UnSelect
// combineLatest failed(message: "Email is wrong") () <- wrong

validation
.withLatestFrom(textField.rx.controlEvent(.editingChanged))

// Select
// No event

// Typing: "A"
// No event

// Typing: "Aa"
// withLatestFrom () failed(message: "Email is wrong") <- correct

// UnSelect
// withLatestFrom () failed(message: "Email is wrong") <- wrong

您知道解决我的问题的其他方法吗?

最佳答案

在你的 viewDidLoad() 中试试这个:

textField.rx.text.orEmpty
.map { $0.isValidEmail }
.subscribe(onNext: { isValid in
print("email is \(isValid ? "" : "Not") Valid")
})

上面使用了这个扩展:

extension String {
var isValidEmail: Bool {
let emailRegex = "[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?"
let predicate = NSPredicate(format: "SELF MATCHES %@", emailRegex)
return predicate.evaluate(with: self)
}
}

关于swift - 如何使用 RxSwift 观察 UITextField 中的输入变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57472261/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com