英文:
how to use if #available(iOS 16.0, *) for a VARIABLE. not in the body?
问题
我试图在 iOS 版本 < 15.0 时不编译 env 变量 requestReview。
如果 #available 在主体中起作用但对变量不起作用,我该怎么办?
结构体 HomeView11labs:View {
// 用于评论
如果 #available(iOS 16.0, *) {
@Environment(\.requestReview) var requestReview: RequestReviewAction
}
}
英文:
I'm trying to not compile the env var requestReview if the ios version is < 15.0
if #available works in the body but doesnt' work for variables, what can I do?
struct HomeView11labs: View {
//for the review
if #available(iOS 16.0, *) {
@Environment(\.requestReview) var requestReview: RequestReviewAction
}
答案1
得分: 1
你可以创建一个函数,该函数将检查iOS版本并相应地运行审核函数 - 确保它是一个@MainActor
函数以在主线程上运行它。
编辑 - 所以我发现我们只能在视图内部使用@Environment
,而不能在函数内部使用,因此我将其放在了一个视图修饰符中,该修饰符将根据iOS版本在@Binding
变量更改时运行请求审核函数,现在这应该大部分给您想要的效果。
@available(iOS 16, *)
struct ReviewModifier: ViewModifier {
@Binding var canRequestReview: Bool
@Environment(\.requestReview) var requestReview
func body(content: Content) -> some View {
content
.onChange(of: canRequestReview) { newValue in
if newValue {
requestReview.callAsFunction()
} else {
SKStoreReviewController.requestReview()
}
}
}
}
extension View {
@ViewBuilder func requestReview(_ canRequestReview: Binding<Bool>) -> some View {
if #available(iOS 16, *) {
modifier(ReviewModifier(canRequestReview: canRequestReview))
} else {
self
}
}
}
英文:
You can create a function that will check the iOS version and run the review function accordingly - make sure it's a @MainActor
function to run it on the Main thread.
Edit - So I found out that we can use the @Environment
only inside a view and not a function hence I put in in a view modifier that will run the request review function depending on the iOS version whenever the @Binding
variable is changed and now this should mostly give you what you want.
@available(iOS 16, *)
struct ReviewModifier: ViewModifier {
@Binding var canRequestReview: Bool
@Environment(\.requestReview) var requestReview
func body(content: Content) -> some View {
content
.onChange(of: canRequestReview) { newValue in
if newValue {
requestReview.callAsFunction()
} else {
SKStoreReviewController.requestReview()
}
}
}
}
extension View {
@ViewBuilder func requestReview(_ canRequestReview: Binding<Bool>) -> some View {
if #available(iOS 16, *) {
modifier(ReviewModifier(canRequestReview: canRequestReview))
} else {
self
}
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论