Reading time: 1 min

This recipe shows how to implement a multiline text field in SwiftUI that expands automatically. The end result looks like this:

preview1

This feature is available starting in SwiftUI 4 (iOS 16, macOS 12.4).

To allow a TextField to grow as its content text grows, use the axis initializer parameter and set it to .vertical:

TextField("Expandable text field",
        text: $text,
        axis: .vertical)

To set the maximum number of displayed lines, use the lineLimit modifier:

TextField("Expandable text field",
        text: $text,
        axis: .vertical)
  .lineLimit(3)

The TextField will then grow until the maximum number of lines. Should the content text have more lines, the field will become scrollable:

preview2

Finally, you can also set the minimum number of displayed lines alongide the maximum by providing a ClosedRange to lineLimit:

TextField("Expandable text field",
        text: $text,
        axis: .vertical)
  .lineLimit(3...6)

Then, the TextField will always be shown expanded to the lower bound of the range and will grow until it reaches the upper bound:

preview3

Next Post Previous Post