How do I create a multiline TextField in SwiftUI?

iOS 16 – beta

TextFields can be configured to expand vertically using the new axis parameter. Also it takes the lineLimit modifier to limit the lines in the given range:

TextField("Title", text: $text,  axis: .vertical)
    .lineLimit(5...10)

But the lineLimit modifier now also supports more advanced behaviors, like reserving a minimum amount of space and expanding as more content is added, and then scrolling once the content exceeds the upper limit


iOS 14 and 15 – Native SwiftUI

It is called TextEditor

struct ContentView: View {
    @State var text: String = "Multiline \ntext \nis called \nTextEditor"

    var body: some View {
        TextEditor(text: $text)
    }
}

🎁 Dynamic growing height:

If you want it to grow as you type, embed it in a ZStack with a Text like this:

Demo


iOS 13 – Using UITextView

you can use the native UITextView right in the SwiftUI code with this struct:

struct TextView: UIViewRepresentable {
    
    typealias UIViewType = UITextView
    var configuration = { (view: UIViewType) in }
    
    func makeUIView(context: UIViewRepresentableContext<Self>) -> UIViewType {
        UIViewType()
    }
    
    func updateUIView(_ uiView: UIViewType, context: UIViewRepresentableContext<Self>) {
        configuration(uiView)
    }
}

Usage

struct ContentView: View {
    var body: some View {
        TextView() {
            $0.textColor = .red
            // Any other setup you like
        }
    }
}

💡 Advantages:

  • Support for iOS 13
  • Shared with the legacy code
  • Tested for years in UIKit
  • Fully customizable
  • All other benefits of the original UITextView

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)