該
然后我嘗試了一個 TextEditor,但這缺乏定義標簽的能力。標簽的位置使得 Form 元素對 MacOS 非常有用,因為它允許標簽正確對齊而無需任何黑客攻擊。缺少邊框樣式只是一個小問題,可以使用邊框樣式解決:
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)
TextEditor(text: $notes)
}
.padding()
.frame(height: 150)
}
}

我只對面向未來的干凈解決方案感興趣。如果沒有,hack 必須至少非常靈活,即所有標簽必須正確對齊。來自workingdog 的解決方案不適合我,因為一旦標簽文本發生變化,一切都會分崩離析。
uj5u.com熱心網友回復:
這種方法怎么樣(根據您的需要進行調整):
struct ContentView: View {
@State var field1 = ""
@State var field2 = ""
@State var notes = ""
var body: some View {
VStack (alignment: .leading, spacing: 20) {
Form {
TextField("Label", text: $field1)
TextField("Long Label", text: $field2)
}
HStack (alignment: .top) {
Spacer().frame(width: 30)
Text("Notes")
TextEditor(text: $notes).frame(height: 200)
}
}
.padding()
.frame(height: 400)
}
}
uj5u.com熱心網友回復:
我個人更喜歡overlay在這種情況下使用相同的視圖,如下所示:
Form {
TextField("Label", text: $field1)
TextField("Long Label", text: $field2)
TextEditor(text: $notes)
.overlay(
TextEditor(text: .constant("label"))
.allowsHitTesting(false)
.opacity(notes.isEmpty ? 1 : 0)
)
}
缺點是它TextEditor不像大多數其他 SwiftUI 視圖那樣作業:它自己繪制默認背景。您可以使用此 hack使游標通過覆寫層可見,并自己在 main 上繪制背景TextEditor。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/376247.html
