gpt4 book ai didi

swiftui - 如何让 TextEditor 显示多行?

转载 作者:行者123 更新时间:2023-12-03 23:45:20 31 4
gpt4 key购买 nike

我想让 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)我总是一次只能看到一行文本编辑器

如何实现?

最佳答案

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

demo

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

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

默认

[ demo1

大字体设置

[ demo2

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: $0.frame(in: .local).size.height)
})
)
.onPreferenceChange(ViewHeightKey.self) { self.textHeight = $0 }
}
}

ViewHeightKey 首选项取自 this my answer

注意:引用文本和 TextEditor 的代码内字体应使用相同的字体

关于swiftui - 如何让 TextEditor 显示多行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63162118/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com