我一直在尝试在SwiftUI中创建多行TextField,但是我不知道怎么做。
这是我目前拥有的代码:
struct EditorTextView : View {
@Binding var text: String
var body: some View {
TextField($text)
.lineLimit(4)
.multilineTextAlignment(.leading)
.frame(minWidth: 100, maxWidth: 200, minHeight: 100, maxHeight: .infinity, alignment: .topLeading)
}
}
#if DEBUG
let sampleText = """
Very long line 1
Very long line 2
Very long line 3
Very long line 4
"""
struct EditorTextView_Previews : PreviewProvider {
static var previews: some View {
EditorTextView(text: .constant(sampleText))
.previewLayout(.fixed(width: 200, height: 200))
}
}
#endif
Run Code Online (Sandbox Code Playgroud)
但这是输出:
我需要一个适用于 MacOS 的 SwiftUI 多行文本输入控件,满足以下要求:
我尝试使用带有 lineLimit() 修饰符的 TextField,它看起来正是我需要的,即标签显示正确(包括对齐),但如果它是空的,并且 RETURN 键不执行任何操作,则它的高度只有 1 行我想要(即新行):
struct ContentView: View {
@State var field1 = ""
@State var field2 = ""
@State var notes = ""
var body: some View {
Form {
TextField("Label", text: $field1)
TextField("Long Label", text: $field2)
TextField("Notes", text: $notes)
.lineLimit(10)
}
.padding()
.frame(height: 150)
}
}
Run Code Online (Sandbox Code Playgroud)
然后我尝试了文本编辑器,但它缺乏定义标签的能力。标签的位置使得 Form 元素对于 MacOS 非常有用,因为它允许标签正确对齐而无需任何修改。缺少边框样式只是一个小问题,可以使用边框样式解决:
struct ContentView: View {
@State var field1 = ""
@State var field2 = ""
@State …Run Code Online (Sandbox Code Playgroud)