一、@State
二攘宙、@State和@Binding
三屯耸、@StateObject和@Published
四、@Environment
五蹭劈、@EnvironmentObject
一疗绣、@State
State是修飾狀態(tài)屬性的,狀態(tài)屬性改變時會自動刷新視圖铺韧。狀態(tài)屬性聲明為私有屬性多矮,以防止其它視圖訪問它們。從任何線程突變狀態(tài)屬性都是安全的。
struct ContentView: View {
@State private var showState: String = "默認顯示State"
var body: some View {
VStack{
Text(showState).padding()
Text("點擊更改State" ) .onTapGesture {
showState = "State已經(jīng)被更改了"
}
}
}
}
二塔逃、@State和@Binding
@State和@Binding結(jié)合使用實現(xiàn)了MVVM模式讯壶。視圖傳@State修飾的參數(shù)時,須使用@Binding修飾的屬性接收參數(shù)湾盗,從而實現(xiàn)雙向綁定伏蚊,保證數(shù)據(jù)實時更新。
struct BindingView: View {
@State private var paramState: String = "State傳參"
var body: some View {
VStack{
ParamView(paramState: $paramState)
Text("點擊State傳參" ).onTapGesture {
paramState = "State傳參成功格粪!"
}
}
}
struct ParamView:View {
@Binding var paramState:String
var body:some View{
Text(paramState).padding()
Text("內(nèi)部改變參數(shù)").padding().onTapGesture {
paramState = "State在內(nèi)部修改成功躏吊!"
}
}
}
}
三、@StateObject和@Published
@StateObject是修飾class實例的狀態(tài)屬性帐萎,該實例的狀態(tài)屬性改變時會自動刷新視圖比伏。該實例須實現(xiàn)ObservableObject協(xié)議,該實例的屬性用@Published修飾疆导。
struct StateObjectView: View {
@StateObject var model = StateModel(name: "默認名字",age: 18)
var body: some View {
VStack{
Text(model.name).padding()
Text("點擊更改StateObject" ).onTapGesture {
model.name = "星星編程"
}
}
}
class StateModel:ObservableObject {
@Published var name: String
@Published var age: Int
init(name: String, age: Int) {
self.name = name
self.age = age
}
}
}
四赁项、@Environment
@Environment是獲取系統(tǒng)環(huán)境變量的。例如isEnabled澈段,editMode悠菜,presentationMode,horizontalSizeClass均蜜,verticalSizeClass等李剖。
struct EnvironmentView: View {
@Environment(\.editMode) var mode
var body: some View {
VStack{
EditButton()
if mode?.wrappedValue == .active{
Text("完成編輯").padding()
} else {
Text("開始編輯").padding()
}
}
}
}
五、@EnvironmentObject
@EnvironmentObject是自定義的環(huán)境對象囤耳,須實現(xiàn)ObservableObject協(xié)議篙顺,該對象的屬性用@Published修飾,可以跨視圖傳參充择、反向傳參德玫,保證數(shù)據(jù)實時更新。
創(chuàng)建EnvironmentModel環(huán)境對象椎麦。
class EnvironmentModel:ObservableObject {
@Published var id: Int
@Published var name: String
init(id: Int,name: String) {
self.id = id
self.name = name
}
}
創(chuàng)建EnvironmentObjectView視圖宰僧。
struct EnvironmentObjectView: View {
@EnvironmentObject var model: EnvironmentModel
var body: some View {
Text(model.name)
}
}
給EnvironmentObjectView傳值。
EnvironmentObjectView().environmentObject(EnvironmentModel(id:888,name: "星星編程"))