How do I create a multiline TextField in SwiftUI?

iOS 14 – 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