SwiftUI仅在特定条件下允许切换

ev7lccsx  于 2023-04-19  发布在  Swift
关注(0)|答案(4)|浏览(110)

我的应用程序有付费功能。我有一个用户可以切换的切换。如果用户没有支付,那么当用户尝试切换切换时,应该会出现一个工作表(并且切换不应该被激活)。如果用户已经支付,那么切换可以切换开和关,没有问题。
我不明白一个简单的结构体(PaidFeature)如何访问一个可观察对象(Model)。我如何在SwiftUI中编写它?

class Model: ObservableObject {
    @Published var hasUserPaid: Bool = false
}

struct PaidFeature {
    var isEnabled = false
}

struct ContentView: View {
    @State private var feature = PaidFeature()
    @EnvironmentObject var model: Model

    
    var body: some View {
        Toggle(isOn: self.$feature.isEnabled) {
            Text("Hello, World!")
        }
    }
}
j5fpnvbx

j5fpnvbx1#

使用Xcode 12,您可以使用.onChange修饰符监听切换按钮的更改,每当用户切换按钮时,您可以将其切换回上一个状态,如果用户不是高级用户,则显示purchase this表单。

.onChange(self.feature.isEnabled) { isEnabled in
                    if isEnabled && shouldShowPurchaseSheet {
                        // toggle back if you want the button to go to the inactive state
                        // show the sheet
                    }
                }
x0fgdtte

x0fgdtte2#

您可以将disabled修改器添加到Toggle

struct ContentView: View {

    @State private var feature = PaidFeature()
    @EnvironmentObject var model: Model

    var body: some View {
        Toggle(isOn: self.$feature.isEnabled) {
            Text("Hello, World!")
        }.disabled(!model.hasUserPaid)
    }
}
ifmq2ha2

ifmq2ha23#

我想应该是

var body: some View {
    Toggle(isOn: self.$feature.isEnabled) {
        Text("Hello, World!")
    }
    .disabled(!model.hasUserPaid)     // << here !!
}

**更新:**带显示表的替代变体演示。在Xcode 12 / iOS 14下测试

为简单起见,所有演示的所有状态都保留在视图中

struct DemoView: View {
    @State private var feature = false
    @State private var paid = false
    @State private var showPurchase = false

    var body: some View {
        Toggle(isOn: $feature) {
            Text("Hello, World!")
        }
        .allowsHitTesting(paid)
        .contentShape(Rectangle())
        .simultaneousGesture(TapGesture().onEnded {
            if !self.paid {
                self.showPurchase = true
            }
        })
        .sheet(isPresented: $showPurchase) {
            Text("Purchase this")
                .onDisappear {
                    self.paid = true
                }
        }
    }
}
niwlg2el

niwlg2el4#

You can use condition in body查看

if self.model.hasUserPaid == true {
   Toggle(isOn: self.$feature.isEnabled)) {
      Text("Hello, World!")
   }
} else {
   Toggle(isOn: .constant({default Bool})) {
      Text("Hello, World!")
   }
}

相关问题