Limit Textfield characters in SwiftUI
Motivation
We want to prevent the user from entering more than X amount of characters in a form.
class TextBindingManager: ObservableObject {
@Published var text = "" {
didSet {
if text.count > characterLimit && oldValue.count <= characterLimit {
text = oldValue
}
}
}
let characterLimit: Int
init(limit: Int = 1){
characterLimit = limit
}
}
struct CharacterInputCell: View {
@ObservedObject var textBindingManager = TextBindingManager(limit: 1)
var body: some View {
TextField("", text: $textBindingManager.text, onEditingChanged: onEditingChanged(_:), onCommit: onCommit)
.frame(maxWidth: .infinity, alignment: .center)
.padding([.trailing, .leading], 10)
.padding([.vertical], 15)
.lineLimit(1)
.multilineTextAlignment(.center)
.overlay(
RoundedRectangle(cornerRadius: 6)
.stroke(Color.red.opacity(0.5), lineWidth: 2)
)
}
}
Sources: 1