如何让 TextEditor 显示多行?

How to get the TextEditor to display multiple lines?

我想让 TextEditor 显示例如。三行文字。我有一些这样的示例代码:

import SwiftUI

struct MultiLineText: View {
    @State var value: String
    @State var text: String
    
    var body: some View {
        Form {
            TextField("Title", text: $value)
            TextEditor(text: $text)
        }
    }
}

struct MultiLineText_Previews: PreviewProvider {
    static var previews: some View {
        MultiLineText(value: "my title", text: "some text")
    }
}

问题是,我总是一次只能看到两个控件(TextEditorTextField)的一行,尽管我希望 [=11= 显示多行].

如何实现?

这就是表单的工作原理。可能的(简单的)解决方案是给 TextEditor 一个框架

TextEditor(text: $text)
    .frame(height: 80)

更新:更复杂的情况(根据参考文本动态计算,并考虑动态字体大小)

默认

[

大字体设置

[

let lorem = "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."

struct ContentView: View {
    @State var value: String = lorem
    @State var text: String = lorem

    @State private var textHeight = CGFloat.zero
    var body: some View {
        Form {
            TextField("Title", text: $value)
            TextEditor(text: $text)
                .frame(minHeight: textHeight)
        }
        .background(
            Text("0\n0\n0")  // any stub 3 line text for reference
                .padding(.vertical, 6)  // TextEditor has default inset
                .foregroundColor(.clear)
                .lineLimit(3)
                .background(GeometryReader {
                    Color.clear
                        .preference(key: ViewHeightKey.self, value: [=11=].frame(in: .local).size.height)
                })
        )
        .onPreferenceChange(ViewHeightKey.self) { self.textHeight = [=11=] }
    }
}

ViewHeightKey 偏好取自

注意:in-code参考字体Text和TextEditor应该使用相同的

backup