Expanding TextFields in SwiftUI
SwiftUI's latest API introduces a powerful feature for TextFields: the ability to expand based on content. This enhancement allows for a more dynamic and responsive user interface.
The New API
The key to this functionality is the axis
parameter in the TextField initializer. It allows you to specify whether the TextField should expand horizontally, vertically, or both.
Code Example
struct ExpandingTextField: View {
@State private var text = ""
var body: some View {
TextField("Enter text", text: $text, axis: .vertical)
.lineLimit(1...5)
.textFieldStyle(.roundedBorder)
}
}
In this example, the TextField expands vertically as the user types, with a minimum of 1 line and a maximum of 5 lines. The roundedBorder
style adds a visual boundary.
Benefits
This feature improves user experience by providing a more intuitive input method for longer text entries, adapting to content length without sacrificing screen real estate.