目标:我想限制 SwiftUI TextField 输入最多 3 个字符。
结果:由于某种原因,有一种方法可以在 TextField 中输入超过 3 个字符
步骤:
其他信息
getter
和setter
打印不打印“1234”输出,这真的很奇怪问题:如何限制/验证给定示例的 SwiftUI TextField 输入?
游乐场代码:
import SwiftUI
import PlaygroundSupport
import Combine
struct ContentView: View {
@State var inputValue: String = ""
@State var previousValue: String = ""
func getter() -> String {
print("getter called with ", inputValue)
return inputValue
}
func setter(_ newValue: String) {
print("setter called with ", inputValue)
if newValue.count > 3 {
inputValue = previousValue
} else {
inputValue = newValue
previousValue = inputValue
}
}
var body: some View {
TextField("", text: .init(get: getter, set: setter))
.frame(minWidth: 100)
}
}
PlaygroundPage.current.setLiveView(ContentView())
此外,即使您更新 TextField 定义,例如:
var body: some View {
TextField("", text: .init(get: { "test "}, set: { _ in }))
.frame(minWidth: 100)
}
要始终强制“测试”值,您仍然可以在每三次尝试中输入附加字符
这可以使用
.onChange
视图修改器来处理。如果我的语法有点偏差,请抱歉,我的 IDE 无法立即可用。
在 SwiftUI 中,你永远不应该真正使用直接的 getter 和 setter。
@State var yourText = ""
var body: some View {
VStack {
// Your Text w/ @State Binding
}
.onChange(of: yourText) { newValue in
// Handle your constraints here.
// Check your value, if it exceeds your 3 char
// reset it back to the limit.
}
}
.onChange
已更改为直接使用闭包内部的 yourText
绑定值,而不是闭包属性。
.onChange(of: yourText) {
// Handle your constraints here.
// Use the `yourText` binding property instead of capturing `newValue`
}