我想你可能会称之为“条件绑定”。我不知道还能怎么称呼它。
当我在文本字段中键入内容或点击按钮时,我想更改标题文本。但是,我不想在点击按钮时更改 TextField 文本,只想更改标题文本。这是演示代码
class Hobbit: ObservableObject {
@Published var firstName: String
init(name: String = "Bilbo") {
self.firstName = name
}
}
struct HobbitView: View {
@StateObject private var hobbit = Hobbit()
var body: some View {
//"Place Holder" should not be modified by tapping the button
TextField("Place Holder", text: $hobbit.firstName)
.padding(.bottom)
//Should be modifiable by TextField or Button
Text("The name is \(hobbit.firstName).")
.font(.title)
//Should only modify the Text, not the TextField text
Button("Set a Name") {
hobbit.firstName = "Sam"
}
}
}
我是 SwiftUI 新手,我认为我缺少一些关于 SwiftUI 绑定如何工作的关键知识。
首先你必须牢记 @State 和 @StateObject 为你的视图数据创建一个事实来源,并且在状态变量创建绑定之前使用 $ 前缀,这是视图和视图之间的双向连接。基础数据。 当您在 TextField 和 Text 视图中使用 $hobbit.firstName 时,它们都直接连接到相同的事实来源。对 hobbit.firstName 的任何更改都会更新两个视图。
因此,在视图中,您必须分离状态变量并专门为标题文本引入一个新的 @State 变量,然后在按钮的操作中更新此状态变量,保持 hobbit.firstName 不变
struct HobbitView: View {
@StateObject private var hobbit = Hobbit()
@State private var titleText = "The name is Bilbo." // New state for title
var body: some View {
TextField("Place Holder", text: $hobbit.firstName)
.padding(.bottom)
Text(titleText) // Use the separate state for title
.font(.title)
Button("Set a Name") {
titleText = "The name is Sam." // Update only titleText
}
}
}