【问题标题】:Conditionally present ActionSheet SwiftUI有条件地呈现 ActionSheet SwiftUI
【发布时间】:2020-06-26 01:30:51
【问题描述】:

我创建了一个更新表来通知我的用户有关更新,但我不希望每次推送更新时都显示它,因为有时它只是错误修复,所以我创建了一个常量来切换表。我正在调用下面的表格:

VStack {
    Text(" ")
}
.sheet(isPresented: $isShowingAppStoreUpdateNotification) {
    UpdatesView()
}

如何有条件地检查常量?这是我尝试过的:

if(generalConstants.shouldShowUpdateSheet) {
    .sheet(isPresented: $isShowingAppStoreUpdateNotification) {
        UpdatesView()
    }
}

但我收到此错误:Cannot infer contextual base in reference to member 'sheet'

【问题讨论】:

    标签: swiftui


    【解决方案1】:

    .sheet 是一个实例方法VStack,所以你不能做你所做的——这不是合法的 Swift 语法。

    最简单的方法是在VStack 视图上设置条件:

    if(generalConstants.shouldShowUpdateSheet) {
       VStack {
          Text(" ")
       }
       .sheet(isPresented: $isShowingAppStoreUpdateNotification) {
          UpdatesView()
       }
    } else {
       VStack {
          Text(" ")
       }
    }
    

    但是,当然,这不是很干燥。

    相反,保持视图在视图模型/状态中的行为逻辑,让视图只对数据变化做出反应。我的意思是,只有在满足您想要的所有条件时才将isShowingAppStoreUpdateNotification 设置为true,并保持视图原样

    @State var isShowingAppStoreUpdateNotification = generalConstants.shouldShowUpdateSheet
    
    var body: some View {
       VStack {
          Text(" ")
       }
       .sheet(isPresented: $isShowingAppStoreUpdateNotification) {
          UpdatesView()
       }
    }
    
    

    【讨论】:

      【解决方案2】:

      这是我的示例代码。

      struct ContentView: View {
          @State private var showSheet = false
          @State private var toggle = false {
              didSet {
                  self.showSheet = toggle && sheet
              }
          }
          @State private var sheet = false {
              didSet {
                  self.showSheet = toggle && sheet
              }
          }
          var body: some View {
              VStack {
                  Toggle(isOn: $toggle) {
                      Text("Allow to show sheet")
                  }
                  Button(action: {
                      self.sheet.toggle()
                  }) {
                      Text("Show sheet")
                  }
              }.sheet(isPresented: $showSheet, content: {
                  Text("Sheet")
              })
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2019-11-16
        • 1970-01-01
        • 2020-11-02
        • 1970-01-01
        • 2021-02-08
        • 2023-04-07
        • 2018-03-11
        • 2020-03-20
        • 2015-12-02
        相关资源
        最近更新 更多