Search code examples
swiftui

Dynamic height for TextEditor


I'm trying to fit the TextEditor inside a ScrollView.

Is there a way to make TextEditor only takes up the space that it needs to fit all text?

or simply, how to change the height of the TextEditor dynamically to fit all the text?


Solution

  • iOS 13

    You can use an invisible Text in a ZStack to make it dynamic.

    ZStack {
        TextEditor(text: $text)
        Text(text).opacity(0).padding(.all, 8) // <- This will solve the issue if it is in the same ZStack
    }
    

    Note that you should consider changing font size and other properties to match the TextEditor

    Here I used it in a list for demo:

    Preview


    iOS 16

    If you are just looking for a vertical growing input field, there is a parameter called axis in TextField that causes the field to grow vertically if needed:

    TextField("", text: $text, axis: .vertical)
    

    Note that if you test with the mac keyboard, you need to hold option for new lines.