在beta6 SwiftUImacOS(不是 iOS)应用中,我需要List具有可编辑的文本字段,但是TextField列表中的s是不可编辑的。它工作正常,如果我换出List了Form(或仅仅VStack),但我需要它工作List。有什么技巧告诉列表使字段可编辑吗?
import SwiftUI
struct ContentView: View {
@State var stringField: String = ""
var body: some View {
List { // works if this is VStack or Form
Section(header: Text("Form Header"), footer: Text("Form Footer")) {
TextField("Line 1", text: $stringField).environment(\.isEnabled, true)
TextField("Line 2", text: $stringField)
TextField("Line 3", text: $stringField)
TextField("Line 4", text: $stringField)
TextField("Line 5", text: $stringField)
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我更新了该项目以针对 MacOS 应用程序,并发现了您报告的错误。我已向 Apple 更新了此反馈,因为它确实似乎是一个错误(欢迎使用 Beta)。
FB7174245 - 当目标是 macOS 时,嵌入列表中的 SwiftUI 文本字段不可编辑
那么下面对状态和绑定的关注有什么意义呢?一个变量应该绑定到一个控件。这是一个工作示例。我将保留旧的答案,因为它通过完整的应用程序保存和检索 CoreData 的数据来推进示例。
import SwiftUI
struct ContentView: View {
@State var field1: String = ""
@State var field2: String = ""
@State var field3: String = ""
@State var field4: String = ""
@State var field5: String = ""
var body: some View {
List { // works if this is VStack or Form
Section(header: Text("Form Header"), footer: Text("Form Footer")) {
TextField("Line 1", text: $field1).environment(\.isEnabled, true)
TextField("Line 2", text: $field2)
TextField("Line 3", text: $field3)
TextField("Line 4", text: $field4)
TextField("Line 5", text: $field5)
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Run Code Online (Sandbox Code Playgroud)
顺便说一句 - 这适用于 Xcode Beta (11M392r) 和 MacOS Catalina - 10.15 Beta (19A546d)。
查看此示例,其中包含一个写入 CoreData 的可编辑文本字段,我正在 Github 上构建该文本字段。
查看 @State 和 @Binding 之间的区别,以便您可以从内容视图外部操作数据。(60秒视频)
struct ContentView: View {
// 1.
@State var name: String = ""
var body: some View {
VStack {
// 2.
TextField(" Enter some text", text: $name)
.border(Color.black)
Text("Text entered:")
// 3.
Text("\(name)")
}
.padding()
.font(.title)
}
}
Run Code Online (Sandbox Code Playgroud)
查看以下答案以了解@State的适当用例(SO答案)
| 归档时间: |
|
| 查看次数: |
727 次 |
| 最近记录: |