SwiftUI: TextField max limit
Aug 3, 2022
TextField is a control that displays an editable text interface.
In this blog, we’ll learn how to set the maximum limit of a text in Textfield using Combine.
The most elegant (and simple) way to set a character limit on the TextField is to use the native publisher event collect()
.
collect()
Collects all received elements, and emits a single array of the collection when the upstream publisher finishes.
import SwiftUI
import Combinestruct ContentView: View {
@State var text = ""
var body: some View { TextField("Set the max length", text: $text)
.font(Font.system(size: 16))
.foregroundColor(Color.blue)
.onReceive(text.publisher.collect()){
let result = String($0.prefix(240))
if text != result {
text = result
}
}
Text("\(text.count)/240 Characters") }
}
Reference taken from,
https://stackoverflow.com/questions/56476007/swiftui-textfield-max-length