Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic height for TextEditor

Tags:

swiftui

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?

like image 1000
umayanga Avatar asked Jun 09 '26 21:06

umayanga


1 Answers

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.


like image 58
Mojtaba Hosseini Avatar answered Jun 12 '26 11:06

Mojtaba Hosseini



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!