swift - swift - 使用SwiftUI将TextField限制为x个字符

我使用iOS13 2,Swift—5.1.2,Xcode—11.2,尝试以下操作:

我想使用TextField ,限制用户只能在TextField中输入x个字符。

我的代码如下所示:


import Combine


import SwiftUI



class Entry: ObservableObject {



 @Published var entry ="" {


 didSet {


 entry = String(entry.prefix(6)) // trying to limit to 6 characters


 }


 }


}



将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()


 }


}



时间:

在SwiftUI中实现此目的的最简单方法是,在达到最大字符数时禁用TextField :


struct LimittedTextField: View {



 @State private var entry =""



 let characterLimit = 6



 var body: some View {


 TextField("", text: $entry)


 .disabled(entry.count > (characterLimit - 1))


 }


}



Entry类可以重写:


class Entry: ObservableObject {



 let characterLimit = 6 // limiting to 6 characters


 @Published var entry ="" {


 didSet {


 if entry.count > characterLimit && oldValue.count <= characterLimit {


 entry = oldValue


 }


 }


 }


}



...