问题描述
使用iOS13.2,Swift-5.1.2,Xcode-11.2,我尝试以下操作:
Using iOS13.2, Swift-5.1.2, Xcode-11.2, I try the following:
我想使用一个TextField.用户只能在文本字段中输入x个字符.
I want to use a TextField. The user shall only be able to enter x-amount of characters into the TextField.
我的代码如下:
import Combine
import SwiftUI
class Entry: ObservableObject {
@Published var entry = "" {
didSet {
entry = String(entry.prefix(6)) // trying to limit to 6 characters
}
}
}
在上面的代码中,已经有例外行.
And in the above code, there is already the exception line.
我可以看到 didSet {...}
是错误的(因为我们最终一次又一次地处于无穷循环设置/didSetting中)...
I can see that the didSet{...}
is wrong (since we end up in an endless loop setting/didSetting again and again)...
将TextField限制为x个字符的更好方法是什么?
这是其余的代码:
struct NumberView: View {
var body: some View {
Group {
HStack {
Spacer()
NumberIcon(number: 1)
NumberIcon(number: 2)
NumberIcon(number: 3)
NumberIcon(number: 4)
NumberIcon(number: 5)
NumberIcon(number: 6)
Spacer()
}
}
}
}
struct NumberIcon: View {
@ObservedObject private var entry = Entry()
var number: Int = 0
var body: some View {
TextField(" ", text: $entry.entry, onEditingChanged: { editing in
print(editing)
print(self.$entry)
})
.padding()
.foregroundColor(Color.black)
.background(Color.green)
.font(.largeTitle)
.lineLimit(1)
.cornerRadius(16.0)
.clipped()
.keyboardType(.numberPad)
}
}
struct NumberView_Previews: PreviewProvider {
static var previews: some View {
NumberView()
}
}
我知道有UIKit包装器可以使用UITextFieldDelegate形式的老式 shouldChangeCharactersIn
委托方法-但我想纯粹通过SwiftUI(无UIKit代码)实现字符限制.我该怎么办?
I know that there are UIKit wrapper possibilities to use the good-old shouldChangeCharactersIn
delegate methods form UITextFieldDelegate - but I would like to implement the character limitation purely with SwiftUI (no UIKit code). How can I do that ?
推荐答案
在SwiftUI中实现此目的的最简单方法是在达到最大字符数时禁用TextField:
The easiest way to achive this in SwiftUI is just to disable the TextField when the maximum number of characters is reached:
struct LimittedTextField: View {
@State private var entry = ""
let characterLimit = 6
var body: some View {
TextField("", text: $entry)
.disabled(entry.count > (characterLimit - 1))
}
}
这篇关于使用SwiftUI将TextField限制为x个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!