Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

Create A Scrollable Text Field in SwiftUI
Written by Team Kodeco

SwiftUI provides a variant of the TextField initializer that allows the creation of a scrollable text field. This initializer is especially useful when you need to display or edit a large amount of text that doesn’t fit into the available space.

Here’s an example of how to create a scrollable text field in SwiftUI:

struct ContentView: View {
  @State private var text = "A long string of text that goes on and on and on and on and on and on and on and on..."

  var body: some View {
    TextField("Enter text here", text: $text, axis: .vertical)
      .padding()
  }
}

Here’s what the preview looks like:

A scrollable text field in SwiftUI.
A scrollable text field in SwiftUI.

In this code:

  • @State private var text = "A long string of text that goes on and on and on and on and on and on and on and on..." creates a state variable, text, that stores the text to be displayed and edited in the text field.

  • TextField("Enter text here", text: $text, axis: .vertical) creates a scrollable text field. The string “Enter text here” is the prompt that appears in the text field until the user types in their own text. The text state variable holds the text input entered by the user. The argument axis: .vertical specifies that the text field should scroll vertically when the amount of text exceeds the available space.

  • .padding() adds padding around the text field.

With this initializer, you can create text fields that scroll their content when the text doesn’t fit in the available space, thereby providing a more user-friendly text editing experience in your SwiftUI apps.

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2024 Kodeco Inc.