Apr 12, 2024 iOS

How do I create a multiline TextField in SwiftUI?

In SwiftUI, the TextField view doesn’t inherently support multiline text input. However, you can achieve multiline text input behavior by using the TextEditor view instead, which is designed for multiline text input. Here’s how you can create a multiline text input using TextEditor:

import SwiftUI

struct ContentView: View {
    @State private var text: String = ""

    var body: some View {
        VStack {
            Text("Enter your text:")
            
            TextEditor(text: $text)
                .frame(minWidth: 0, maxWidth: .infinity, minHeight: 100, maxHeight: .infinity) // adjust size as needed
                .border(Color.gray, width: 1) // add border for visual clarity
                .padding() // add padding for better appearance
        }
        .padding()
    }
}

In this example, TextEditor is used instead of TextField. You bind TextEditor to a @State property (text in this case) to keep track of the text input. Additionally, you can adjust the frame to set the size of the TextEditor as per your requirement.

Remember that TextEditor is only available starting from iOS 14.0, macOS 11.0, Mac Catalyst 13.0, tvOS 14.0, and watchOS 7.0. If you need to support earlier versions, you may need to find alternative solutions or libraries.

Creating a multiline TextField in SwiftUI can be achieved using different approaches based on the iOS version you are targeting. Let’s explore a few options:

  1. iOS 16+ (Using TextField with axis parameter): You can configure a TextField to expand vertically by specifying the axis: .vertical parameter. Additionally, you can use the .lineLimit modifier to limit the number of lines. Here’s an example:
TextField("Title", text: $text, axis: .vertical)
    .lineLimit(5...10)
  1. The .lineLimit modifier now supports advanced behaviors, such as reserving a minimum amount of space and expanding as more content is added, with scrolling once the content exceeds the upper limit1.
  2. iOS 14+ (Using TextEditor): SwiftUI introduced the TextEditor view for multiline text input. It automatically grows as you type. Here’s an example:
struct ContentView: View {
    @State var text: String = "Multiline\ntext\nis called\nTextEditor"
    var body: some View {
        TextEditor(text: $text)
    }
}