SwiftUI:绑定到@AppStorage
Posted
技术标签:
【中文标题】SwiftUI:绑定到@AppStorage【英文标题】:SwiftUI: Binding to @AppStorage 【发布时间】:2021-07-17 17:05:20 【问题描述】:在以下示例中,如何根据 SwiftUI 更新 aArrived
和 bArrived
的方式更改 activeSheet
的值?
struct ContentView: View
@AppStorage("didAArrive") var aArrived: Bool = false
@AppStorage("didBArrive") var bArrived: Bool = false
enum ActiveSheet: Identifiable
case aArrived, bArrived
var id: Int
hashValue
@State private var activeSheet: ActiveSheet?
var body: some View
Text("Hello")
.sheet(
item: $activeSheet,
content: item in
switch item
case .aArrived:
Text("A arrived")
case .bArrived:
Text("B arrived")
)
【问题讨论】:
whatArrived
是否会独立于aArrived
或bArrived
而改变?如果不是,请不要将其设为 @State
变量,只需将其设为计算属性即可。
我需要它作为 sheet(item:) 修饰符的 item 参数,所以我认为我需要它是 State。
那只是意味着它需要是一个Binding。这将有助于根据要求更新问题。否则,听起来您已经知道如何使用 onAppear 和 onChange。
【参考方案1】:
您可以为根据aArrived
和bArrived
获取其值的工作表创建自定义绑定。绑定值将根据aArrived
或bArrived
进行初始化,并在每次任一更改时更新。
struct ContentView: View
@AppStorage("didAArrive") var aArrived: Bool = false
@AppStorage("didBArrive") var bArrived: Bool = false
enum ActiveSheet: Identifiable
case aArrived, bArrived
var id: Int
hashValue
var body: some View
let sheetBinding = Binding<ActiveSheet?>(
get:
if aArrived && bArrived
return ActiveSheet.aArrived
else if aArrived
return ActiveSheet.aArrived
else if bArrived
return ActiveSheet.bArrived
else
return nil
,
set: _ in
)
VStack(spacing: 20)
Toggle("A arrived", isOn: $aArrived)
Toggle("B arrived", isOn: $bArrived)
.sheet(
item: sheetBinding,
content: item in
switch item
case .aArrived:
Text("A arrived")
case .bArrived:
Text("B arrived")
)
【讨论】:
以上是关于SwiftUI:绑定到@AppStorage的主要内容,如果未能解决你的问题,请参考以下文章
如何告诉 SwiftUI 视图绑定到嵌套的 ObservableObjects
有没有办法使用 SwiftUI 将选项绑定到 Toggle / Slider