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:
- iOS 16+ (Using
TextFieldwithaxisparameter): You can configure aTextFieldto expand vertically by specifying theaxis: .verticalparameter. Additionally, you can use the.lineLimitmodifier to limit the number of lines. Here’s an example:
TextField("Title", text: $text, axis: .vertical)
.lineLimit(5...10)
- The
.lineLimitmodifier 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. - iOS 14+ (Using
TextEditor): SwiftUI introduced theTextEditorview 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)
}
}