SwiftUI學習之state和Binding的區(qū)別淺析
@state 綁定值的狀態(tài),其屬性的修飾官方推薦使用private.上代碼(ps:這里沒用private 進行修飾,是為了演示區(qū)別)
import SwiftUI
struct FilterView: View {
// @Binding var isFavorite: Bool
@State var isFavorite = true
var body: some View {
Toggle(isOn: $isFavorite) {
}
let buttonTitle = isFavorite ? "嘔吼" : "頓頓"
Text(buttonTitle)
}
}
struct ProductView: View {
var titleS: String
//:不想讓外部訪問的變量 需要初始化
@State private var changeButtonTtile = true
var body: some View {
Button (action: {
changeButtonTtile.toggle()
}) {
let buttonTitle = changeButtonTtile ? "哈哈哈" : "啦啦啦啦"
Text(buttonTitle)
FilterView(isFavorite: changeButtonTtile)
}
}
}
這里我們看到 @State var isFavorite = true通過state 進行修飾.這個時候我們點擊FilterView的開關 我們只能刷新當前FilterView的界面.注意這里:FilterView(isFavorite: changeButtonTtile) 初始化傳入的是changeButtonTtile的value,也就實際值.
下面我們把State注釋掉 ,打開@Bingding 那一行
import SwiftUI
struct FilterView: View {
@Binding var isFavorite: Bool
// @State var isFavorite = true
var body: some View {
Toggle(isOn: $isFavorite) {
}
let buttonTitle = isFavorite ? "嘔吼" : "頓頓"
Text(buttonTitle)
}
}
struct ProductView: View {
var titleS: String
//:不想讓外部訪問的變量 需要初始化
@State private var changeButtonTtile = true
var body: some View {
Button (action: {
changeButtonTtile.toggle()
}) {
let buttonTitle = changeButtonTtile ? "哈哈哈" : "啦啦啦啦"
Text(buttonTitle)
FilterView(isFavorite: $changeButtonTtile)
//:注意這里的取值 變成了$
}
}
}
這里我們運行代碼,點擊開關,你發(fā)現(xiàn)了什么??.ProductView 的UI 也發(fā)生了變化.這個時候FilterView 傳入的是changeBtnTitle的引用,而不是值.這樣你在子視圖改變@Binding修飾的值,父視圖也會跟著刷新.
使用小結(jié)
- 當自定義視圖的數(shù)據(jù)需要外部傳入的時候, 使用普通的屬性
- 當自定義的視圖需要通過數(shù)據(jù)變化更新視圖時, 對普通屬性加上@State修飾
- 當自定義的視圖需要將視圖的變化表現(xiàn)在數(shù)據(jù)的變化時,對普通屬性加上@Binding修飾, @Binding 包含了@State的功能, 但一般不會去對@Binding屬性做修改
總結(jié)
到此這篇關于SwiftUI學習之state和Binding區(qū)別的文章就介紹到這了,更多相關SwiftUI state和Binding區(qū)別內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
swift3.0 創(chuàng)建sqlite數(shù)據(jù)庫步驟方法
本篇文章主要介紹了swift3.0 創(chuàng)建sqlite數(shù)據(jù)庫步驟方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-06-06
swift 3.0 正則表達式查找/替換字符的實現(xiàn)代碼
正則表達式使用單個字符串來描述、匹配一系列符合某個句法規(guī)則的字符串。本文重點給大家介紹swift 3.0 正則表達式查找/替換字符的實現(xiàn)代碼,需要的朋友參考下吧2017-08-08

