Reading time: 1 min

This quick recipe shows how to limit the length of a SwiftUI TextField input.

The end result looks like this:


Each TextField receives a string binding that represents its text input. The trick here is to subscribe to its publisher in an onReceive and then clip it to the provided maximum length. Here's the full code, wrapped up in a nice ViewModifier that you can attach to your TextFields:

struct TextLengthLimiter: ViewModifier {
  @Binding var text: String
  let maxLength: Int

  func body(content: Content) -> some View {
      .onReceive(text.publisher.collect()) { output in
        text = String(output.prefix(maxLength)) // HERE

extension TextField {
  func limitTextLength(_ text: Binding<String>,
                       to maxLength: Int) -> some View {
    self.modifier(TextLengthLimiter(text: text,
                                    maxLength: maxLength))

Then, you can use it like this:

struct TextLengthLimitTest: View {
  @State private var text = ""

  var body: some View {
    TextField("Limit 3", text: $text)
      .limitTextLength($text, to: 3)

Previous Post