Is it possible to set a maximum length for TextField? I was thinking of handling it using onEditingChanged event but it is only called when the us
Latest edit:
It has been pointed out that since SwiftUI 2, this no longer works, so depending on the version you're using, this may no longer be the correct answer
Original answer:
A slightly shorter version of Paulw11's answer would be:
class TextBindingManager: ObservableObject {
@Published var text = "" {
didSet {
if text.count > characterLimit && oldValue.count <= characterLimit {
text = oldValue
}
}
}
let characterLimit: Int
init(limit: Int = 5){
characterLimit = limit
}
}
struct ContentView: View {
@ObservedObject var textBindingManager = TextBindingManager(limit: 5)
var body: some View {
TextField("Placeholder", text: $textBindingManager.text)
}
}
All you need is an ObservableObject wrapper for the TextField string. Think of it as an interpreter that gets notified every time there's a change and is able to send modifications back to the TextField. However, there's no need to create the PassthroughSubject, using the @Published modifier will have the same result, in less code.
One mention, you need to use didSet, and not willSet or you can end up in a recursive loop.