We’ve used SwiftUI’s TextField
view several times already, and it’s great for times when the user wants to enter short pieces of text. However, for longer pieces of text you might want to switch over to using a TextEditor
view instead: it also expects to be given a two-way binding to a text string, but it has the additional benefit of allowing multiple lines of text – it’s better for giving users a large amount of space to work with.
Mostly because it has nothing special in the way of configuration options, using TextEditor
is actually easier than using TextField
– you can’t adjust its style or add placeholder text, you just bind it to a string. However, you do need to be careful to make sure it doesn’t go outside the safe area, otherwise typing will be tricky; embed it in a NavigationStack
, a Form
, or similar.
For example, we could create the world’s simplest notes app by combining TextEditor
with @AppStorage
, like this:
struct ContentView: View {
@AppStorage("notes") private var notes = ""
var body: some View {
NavigationStack {
TextEditor(text: $notes)
.navigationTitle("Notes")
.padding()
}
}
}
Tip: @AppStorage
is not designed to store secure information, so never use it for anything private.
Now, there's a reason I said you might want to switch over to using a TextEditor
as opposed to saying you should: SwiftUI provides a third option that works better in some situations.
When we create a TextField
, we can optionally provide an axis it can grow along. This means the textfield starts out as a regular, single-line text field, but as the user types it can grow, just like the iMessage text box does.
Here's how that looks:
struct ContentView: View {
@AppStorage("notes") private var notes = ""
var body: some View {
NavigationStack {
TextField("Enter your text", text: $notes, axis: .vertical)
.textFieldStyle(.roundedBorder)
.navigationTitle("Notes")
.padding()
}
}
}
It's worth trying out to see what you think.
You'll use both of these approaches at some point, but at different times. While I love the way TextField
automatically expands, sometimes it's just helpful to be able to show a large text space to your user so they know up front they can type a lot in there.
Tip: SwiftUI often changes the way things look once they are inside a Form
, so make sure and try them both inside and outside a Form
to see how they vary.
SPONSORED Transform your career with the iOS Lead Essentials. This Black Friday, unlock over 40 hours of expert training, mentorship, and community support to secure your place among the best devs. Click for early access to this limited offer and a free crash course.
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.