本文介绍了如何在SwiftUI中检测targetEnvironment是否是iPadOS?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在为 iOS 和 iPadOS 构建时显示不同的视图.目前,我知道我可以做到

I'd like to display different views when building for iOS and iPadOS. Currently, I know I can do

import SwiftUI

struct ContentView: View {
    #if targetEnvironment(macCatalyst)
    var body: some View {
        Text("Hello")
    }
    #else
    var body: some View {
        Text("Hello")
    }
    #endif
}

在 macOS 和 iPadOS/iOS 之间显示不同的视图(在 Swift 4/5 中引入).但我如何区分后者?我似乎无法使用 targetEnvironment ...

to display different views between macOS and iPadOS/iOS (introduced in Swift 4/5). But how do I differentiate between the latter? I can't seem to use targetEnvironment...

推荐答案

我在我的代码中使用了这个:

I use this in my code:

    private var idiom : UIUserInterfaceIdiom { UIDevice.current.userInterfaceIdiom }
    private var isPortrait : Bool { UIDevice.current.orientation.isPortrait }

然后你可以这样做:

    var body: some View {
        NavigationView {
            masterView()

            if isPortrait {
                portraitDetailView()
            } else {
                landscapeDetailView()
            }
        }
    }

    private func portraitDetailView() -> some View {
        if idiom == .pad {
            return Text("iPadOS")
        } else {
            return Text("iOS")
        }
    }

这篇关于如何在SwiftUI中检测targetEnvironment是否是iPadOS?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-16 11:03