Dynamic height for TextEditor

Viewed 1868

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?

3 Answers

You can put it in a ZStack with an invisible Text for sizing:

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

Dynamic height can also be achieved with combination use of Text and overlay() with TextEditor.

Text(textVal.isEmpty ? "Your placeholder" : textVal)
    .font(.body)
    .padding(.vertical, 8)
    .padding(.horizontal, 18)
    .foregroundColor(Color.gray)
    .opacity(textVal.isEmpty ? 1 : 0)
    .frame(maxWidth: .infinity, minHeight: 40, alignment: .leading)
    .background(
        RoundedRectangle(cornerRadius: 5)
            .stroke(Color.gray.opacity(0.2), lineWidth: 1)
            .padding(.horizontal, 15)
    )
    .overlay(
        TextEditor(text: $textVal)
            .font(.body)
            .foregroundColor(Color.black)
            .multilineTextAlignment(.leading)
            .padding(.horizontal, 15)
    )

For transparent background of TextEditor add below code on View init:

init(yourProperty: String) {
    self.yourProperty = yourProperty
    UITextView.appearance().backgroundColor = .clear
}

using

TextEditor(text: someTextBinding)
   .fixedSize(horizontal: false, vertical: true)

does the job for me (== height is dynamic, width is static)

Related