简体   繁体   中英

Change view based on device - SwiftUI

I have designed my app initially for the iPad and am now wanting to add functionality for an iPhone too. Is there a way to check what the device being used is, and then display a view accordingly?

Structured English:

IF current_device == iPhone THEN
    DISPLAY iPhoneView
ELSE IF current_device == iPad THEN
    DISPLAY iPadView

If possible I also want the iPad view to only be available horizontally and then the iPhone view to only be available vertically if possible.

What you are looking for are Size Classes .

To read current horizontal size class in SwiftUI view you can refer to the environment value of horizontalSizeClass

@Environment(\.horizontalSizeClass) var horizontalSizeClass

Then use it like this in your SwiftUI View :

var body: some View {
    if horizontalSizeClass == .compact {
        return CompactView() // view laid out for smaller screens, like an iPhone
    } else {
        return RegularView() // view laid out for wide screens, like an iPad
    }
}

It is worth noting that not all iPhones are compact horizontally, and compact size class is present on iPad while in multitasking configuration. You will find all possible combinations here under the Device Size Classes and Multitasking Size Classes sections.

Some articles that may be helpful

Alternatively you could set an individual threshold based on the devices height (or width) using a variable like this:

@State var isLargeDevice: Bool = {
    if UIScreen.main.bounds.height > 800 {
        return true
    } else {
        return false
    }
}()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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