如何将 fullScreenCover 与 iOS 14 一起使用,但适用于 13 [英] How to use fullScreenCover with iOS 14 but sheet for 13

查看:31
本文介绍了如何将 fullScreenCover 与 iOS 14 一起使用,但适用于 13的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您已经构建了一个使用 sheet API 来呈现模式表的屏幕,现在在 SwiftUI 2.0 中,您希望在 iOS 14 上运行时使用 fullScreenCover. 你是怎么做的?Xcode 提供建议:

Imagine you've built a screen that utilizes the sheet API to present modal sheets, and now with SwiftUI 2.0 you want to use fullScreenCover instead when run on iOS 14. How do you do so? Xcode offers suggestions:

  • 添加 if #available 版本检查
  • 添加@available 属性

如果您使用#available 版本检查,它会使用#available 包装所有范围内的代码,因此您必须复制所有这些以更改该一行代码.如果使用@available,则必须复制整个结构.

If you use the #available version check, it wraps all of that scoped code with #available, so you'd have to duplicate all of that to change that one line of code. If you use @available you have to duplicate the entire struct.

有没有办法让在线"?逻辑是说如果 iOS 14 添加这个修饰符,否则回到这个修饰符,而不必复制所有其余的视图代码?

Is there a way to have "in-line" logic that says if iOS 14 add this modifier, otherwise fall back to this one, without having to duplicate all of the rest of the view code?

示例:

VStack {
    //a lot of other views here
}
.sheet(isPresented: self.$showingSomeView) { //TODO: Replace sheet with fullScreenCover for iOS 14+
    SomeView()
}

推荐答案

这里有可能的方法

struct DemoCompatibleFullScreen: View {
    @State private var activateFullScreen = false
    var body: some View {
        Button("Toggle") { self.activateFullScreen.toggle() }
            .compatibleFullScreen(isPresented: $activateFullScreen) {
                Text("I'm in Full Screen!")
            }
    }
}

extension View {
    func compatibleFullScreen<Content: View>(isPresented: Binding<Bool>, @ViewBuilder content: @escaping () -> Content) -> some View {
        self.modifier(FullScreenModifier(isPresented: isPresented, builder: content))
    }
}

struct FullScreenModifier<V: View>: ViewModifier {
    let isPresented: Binding<Bool>
    let builder: () -> V

    @ViewBuilder
    func body(content: Content) -> some View {
        if #available(iOS 14.0, *) {
            content.fullScreenCover(isPresented: isPresented, content: builder)
        } else {
            content.sheet(isPresented: isPresented, content: builder)
        }
    }
}

这篇关于如何将 fullScreenCover 与 iOS 14 一起使用,但适用于 13的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆