I have a view that contain users UsersContentView
in this view there is a button which is extracted as a subview: RequestSearchButton()
, and under the button there is a Text
view which display the result if the user did request to search or no, and it is also extracted as a subview ResultSearchQuery()
.
struct UsersContentView: View {
var body: some View {
ZStack {
VStack {
RequestSearchButton()
ResultSearchQuery(didUserRequestSearchOrNo: .constant("YES"))
}
}
}
}
struct RequestSearchButton: View {
var body: some View {
Button(action: {
}) {
Text("User requested search")
}
}
}
struct ResultSearchQuery: View {
@Binding var didUserRequestSearchOrNo: String
var body: some View {
Text("Did user request search: (didUserRequestSearchOrNo)")
}
}
How can I update the @Binding var didUserRequestSearchOrNo: String
inside the ResultSearchQuery()
When the button RequestSearchButton()
is clicked. Its so confusing!
2
Answers
Actually I couldn’t understand why you used two struct which are connected to eachother, you can do it in one struct and Control with a state var
if this is not what you are looking for, could you make a detailed explain.
You need to track the State of a variable (which is indicating if a search is active or not) in your parent view, or your ViewModel if you want to extract the Variables. Then you can refer to this variable in enclosed child views like the Search Button or Search Query Results.
In this case a would prefer a Boolean value for the tracking because it’s easy to handle and clear in meaning.