@state The state of the bound value, and its attribute modification is officially recommended to use private. The code above (ps: private is not used for modification here, to demonstrate the difference)
import SwiftUI
struct FilterView: View { // @Binding var isFavorite: Bool @State var isFavorite = true var body: some View { Toggle(isOn: $isFavorite) { } let buttonTitle = isFavorite ? "Roar" : "Don" Text(buttonTitle) } } struct ProductView: View { var titleS: String //: Variables that do not want to be accessed externally need to be initialized @State private var changeButtonTtile = true var body: some View { Button (action: { () }) { let buttonTitle = changeButtonTtile ? "Hahaha" : "Lalala" Text(buttonTitle) FilterView(isFavorite: changeButtonTtile) } } }
Here we see that @State var isFavorite = true is modified through state. At this time, we click the FilterView switch. We can only refresh the interface of the current FilterView. Note here: FilterView(isFavorite: changeButtonTtile) The value passed in the initialization is the changeButtonTtile value, which is the actual value.
Next, we comment out State and open the @Bingding line
import SwiftUI struct FilterView: View { @Binding var isFavorite: Bool // @State var isFavorite = true var body: some View { Toggle(isOn: $isFavorite) { } let buttonTitle = isFavorite ? "Roar" : "Don" Text(buttonTitle) } } struct ProductView: View { var titleS: String //: Variables that do not want to be accessed externally need to be initialized @State private var changeButtonTtile = true var body: some View { Button (action: { () }) { let buttonTitle = changeButtonTtile ? "Hahaha" : "Lalala" Text(buttonTitle) FilterView(isFavorite: $changeButtonTtile) //: Note that the value here becomes $ } } }
Here we run the code and click on the switch. What did you find??. The UI of ProductView has also changed. At this time, the FilterView passes in the reference of changeBtnTitle, not the value. In this way, if you change the value modified by @Binding in the child view, the parent view will also refresh.
Summary of use
- When the data of the custom view needs to be passed in externally, use normal properties
- When a custom view needs to update the view through data changes, add @State to the normal attributes
- When a custom view needs to express the changes in the view in the data, add @Binding to the normal attributes. @Binding includes the function of @State, but generally does not modify the @Binding attribute.
Summarize
This is the end of this article about the difference between state and Binding in SwiftUI learning. For more information about the differences between state and Binding, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!