简体   繁体   English

有条件地存在 ActionSheet SwiftUI

[英]Conditionally present ActionSheet SwiftUI

I created an update sheet to inform my users about updates, but I don't want it to display every time I push an update because sometimes it's just bug fixes, so I created a constant to toggle the sheet.我创建了一个更新表来通知我的用户有关更新,但我不希望每次推送更新时都显示它,因为有时它只是错误修复,所以我创建了一个常量来切换表。 I'm calling the sheet below:我正在调用下面的表格:

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

How can I conditionally check for the constant?如何有条件地检查常量? This is what I tried:这是我尝试过的:

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

But I get this error: Cannot infer contextual base in reference to member 'sheet'但我收到此错误: Cannot infer contextual base in reference to member 'sheet'

Here is my sample code.这是我的示例代码。

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")
        })
    }
}

.sheet is an instance method VStack , so you can't do what you did - it's not a legal Swift syntax. .sheet是一个实例方法VStack ,所以你不能做你所做的 - 它不是合法的 Swift 语法。

The simplest approach is to have the condition over the VStack view:最简单的方法是在VStack视图上设置条件:

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

but, of course, this isn't very DRY.但是,当然,这不是很干燥。

Instead, keep the logic of how the view behaves in the view model / state, and let the View just react to data changes.相反,将视图行为的逻辑保留在视图 model / state 中,并让视图仅对数据更改做出反应。 What I mean is, only set isShowingAppStoreUpdateNotification to true when all the conditions that you want are satisfied, and keep the view as-is我的意思是,只有在满足您想要的所有条件时才将isShowingAppStoreUpdateNotification设置为true ,并保持视图原样

@State var isShowingAppStoreUpdateNotification = generalConstants.shouldShowUpdateSheet

var body: some View {
   VStack {
      Text(" ")
   }
   .sheet(isPresented: $isShowingAppStoreUpdateNotification) {
      UpdatesView()
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM