【发布时间】:2020-08-10 03:48:33
【问题描述】:
我一直在尝试限制我可以在 SwiftUI 中的 TextField 上输入的字符数,同时只允许数字。
.onReceive(Just(viewModel.myString)) { newValue in
let filtered = newValue.filter { "0123456789".contains($0) }
if filtered != newValue {
self.viewModel.myString = filtered
}
}
过滤字符以及
@Published var myString: String = "" {
willSet {
if newValue.count > Constants.maxLimit {
myString = String(newValue.prefix(Constants.maxLimit))
}
}
}
限制字符数。
但是通过这种方法,我仍然可以添加多个Constants.maxLimit 并添加数字以外的字符。
如果我尝试将这两个逻辑与视图模型中的 willSet/didSet 或文本字段中的 onReceive 结合起来,则会因堆栈溢出而导致崩溃。
我还是 SwiftUI 的新手,所以我不确定自定义 Publisher 是否有助于解决我的问题。
【问题讨论】:
-
你不能这样做吗? :
.onReceive(Just(viewModel.myString)) { newValue in let filtered = newValue.filter { "0123456789".contains($0) } if filtered != newValue, filtered.count <= Constants.maxLimit { self.viewModel.myString = filtered } }
标签: ios swift swiftui textfield