how can i define a TextEditor with word wrap and max 4 lines of its content visible?

Generated on 8/1/2024

1 search

To define a TextEditor in SwiftUI with word wrap and a maximum of 4 lines of its content visible, you can use the .frame modifier to limit the height of the TextEditor. Here is an example:

import SwiftUI

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

    var body: some View {
        TextEditor(text: $text)
            .frame(maxHeight: 100) // Adjust the height as needed to fit 4 lines
            .lineLimit(4) // This ensures the TextEditor does not grow beyond 4 lines
            .padding()
            .border(Color.gray, width: 1)
    }
}

In this example:

  • The .frame(maxHeight: 100) limits the height of the TextEditor. You may need to adjust the height value to fit exactly 4 lines based on your font size and line spacing.
  • The .lineLimit(4) ensures that the TextEditor does not grow beyond 4 lines.

For more detailed information on text handling and customization, you can refer to the session Get started with Writing Tools at WWDC 2024.