SwiftUI - 子视图的可变@FocusState?
SwiftUI - Mutable @FocusState for child view?
我有一个带有 @FocusState
变量的父视图,我想将其传递给包含 TextField
的子视图。我希望能够从子视图中更改 FocusState
,但出现错误 Cannot assign to property: 'self' is immutable
和 Cannot assign value of type 'Bool' to type 'FocusState<Bool>.Binding'
。
父视图:
struct ParentView: View {
@State private var text: String
@FocusState private var isEditing: Bool
var body: some View {
ChildView($text, $isEditing)
}
}
struct ChildView: View {
@Binding var text: String
var isEditing: FocusState<Bool>.Binding
init(_ text: Binding<String>, _ isEditing: FocusState<Bool>.Binding) {
self._text = text
self.isEditing = isEditing
}
var body: some View {
TextField("Username", text: $text)
.focused(isEditing)
Button("Click me!") {
isEditing = false // Error here
}
}
}
非常感谢!
只需通过绑定到包装值进行赋值,例如
Button("Click me!") {
isEditing.wrappedValue = false // << here !!
}
我有一个带有 @FocusState
变量的父视图,我想将其传递给包含 TextField
的子视图。我希望能够从子视图中更改 FocusState
,但出现错误 Cannot assign to property: 'self' is immutable
和 Cannot assign value of type 'Bool' to type 'FocusState<Bool>.Binding'
。
父视图:
struct ParentView: View {
@State private var text: String
@FocusState private var isEditing: Bool
var body: some View {
ChildView($text, $isEditing)
}
}
struct ChildView: View {
@Binding var text: String
var isEditing: FocusState<Bool>.Binding
init(_ text: Binding<String>, _ isEditing: FocusState<Bool>.Binding) {
self._text = text
self.isEditing = isEditing
}
var body: some View {
TextField("Username", text: $text)
.focused(isEditing)
Button("Click me!") {
isEditing = false // Error here
}
}
}
非常感谢!
只需通过绑定到包装值进行赋值,例如
Button("Click me!") {
isEditing.wrappedValue = false // << here !!
}