How to make a TextField expand vertically as the user types
How to make a TextField expand vertically as the user types 관련
Updated for Xcode 15
SwiftUI's TextField
has a single line by default, and TextEditor
is a multiline alternative based on how much space you want to allocate. But there's a middle ground: if we pass an axis
parameter to TextField
, we can ask it to start as a single line and grow upwards as the user types, optionally switching to scrolling once the text goes past a certain length.
For example, this creates a TextField
that automatically expands as the user enters more and more text:
struct ContentView: View {
@State private var bio = "About me"
var body: some View {
VStack {
TextField("Describe yourself", text: $bio, axis: .vertical)
.textFieldStyle(.roundedBorder)
Text(bio)
}
.padding()
}
}
You can control how big the TextField
can grow by adding a lineLimit()
modifier. For example, we might want to say that it should start out as a single line, but allow growth up to a maximum of five lines:
struct ContentView: View {
@State private var bio = "About me"
var body: some View {
VStack {
TextField("Describe yourself", text: $bio, axis: .vertical)
.textFieldStyle(.roundedBorder)
.lineLimit(5)
Text(bio)
}
.padding()
}
}
That doesn't mean the user can't type more than five lines, only that once the TextField
goes beyond that limit it will switch to scrolling rather than growing further.
You can pass a range here if you want, for example using lineLimit(2...5)
to mean “always be at least two lines high, but grow up to five.”
You can also use the reservesSpace
parameter to lineLimit()
so that the view automatically allocates enough space for the maximum size it can have. For example, this creates a TextField
that reserves enough layout space to hold up to five lines of text:
struct ContentView: View {
@State private var bio = "About me"
var body: some View {
VStack {
TextField("Describe yourself", text: $bio, axis: .vertical)
.textFieldStyle(.roundedBorder)
.lineLimit(5, reservesSpace: true)
Text(bio)
}
.padding()
}
}
The combination of this growing behavior and its ability to have a placeholder makes TextField
a really great choice for entering user text, and preferable to TextEditor
in situations where you aren't relying on an exact view frame and you don't need search and replace functionality.