TextEditor sticking to minHeight inSwiftUI

Viewed 1865

I am trying to build a view with the newly introduced TextEditor. The idea is that I have some content at the top (blue frame), then a ScrollView with a TextEditor and a variable number of Text below it (red frame).

The TextEditor(yellow frame) view is supposed to have a minimum height, but should take up all the available space if there aren't to many Text views following – which it currently does not do...

enter image description here

import SwiftUI

struct ScrollViewWithTextEditor: View {
    
    var comments = ["Foo", "Bar", "Buzz"]
    
    var loremIpsum = """
    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
    """
    
    var body: some View {
        VStack {
            Group {
                Text("Some Content above")
            }
            .frame(maxWidth: .infinity)
            .border(Color.blue, width: 3.0)
            .padding(.all, 10)

            ScrollView {
                ScrollView {
                    TextEditor(text: .constant(loremIpsum))
                        .frame(minHeight: 200.0)
                }
                .frame(minHeight: 200.0)
                .border(Color.yellow, width: 3.0)
                .cornerRadius(3.0)
                .padding(.all, 10.0)
                
                VStack {
                    ForEach(comments, id: \.self) { comment in
                        Text(comment)
                    }
                    .padding(.all, 10)
                    .frame(maxWidth: .infinity, alignment: .leading)
                    .border(Color.gray, width: 1)
                    .cornerRadius(3.0)
                    .padding(.all, 10)
                }
                
            }
            .frame(minHeight: 200.0)
            .border(Color.red, width: 3)
            .padding(.all, 3)
        }
    }
}

struct ScrollViewWithTextEditor_Previews: PreviewProvider {
    static var previews: some View {
        ScrollViewWithTextEditor()
    }
}

Any suggestions on how to solve this?

1 Answers

Here is possible solution. Tested with Xcode 12 / iOS 14.

demo

ScrollView {
    // make clear static text in background to define size and
    // have TextEditor in front with same text fit
    Text(loremIpsum).foregroundColor(.clear).padding(8)
    .frame(maxWidth: .infinity)
    .overlay(
        TextEditor(text: .constant(loremIpsum))
    )
}
.frame(minHeight: 200.0)
.border(Color.yellow, width: 3.0)
Related