4

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?

umayanga
  • 2,254
  • 3
  • 15
  • 26

4 Answers4

8

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
}
Mojtaba Hosseini
  • 95,414
  • 31
  • 268
  • 278
  • Oh yes. It worked. Thanks Mojtaba. But I faced some more issues. So I decided to use UITextView for now. – umayanga Jul 22 '20 at 03:05
4

using

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

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

Pavel Zak
  • 479
  • 3
  • 11
2

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
}
nurmat
  • 361
  • 3
  • 11
0

there's a nice answer, built in function

https://www.hackingwithswift.com/quick-start/swiftui/how-to-make-a-textfield-expand-vertically-as-the-user-types

TextField(placeholder, text: $value, axis: .vertical)
        .textFieldStyle(.roundedBorder)
aaronium112
  • 2,992
  • 4
  • 35
  • 50