benpomeroy9
benpomeroy9

Reputation: 427

Update variables based on device rotation - Swift UI

I have found and used some code which will return a variable true based on the device size and rotation. However these variables do not update when the device is rotated, and the text does not change. I think I would need to use an observable object but am not sure how I would go about converting this extension? Here is the code I am using below.

ContentView()

    struct ContentView3: View, SizeClassAdjustable {
    
    @Environment(\.verticalSizeClass) var _verticalSizeClass
    @Environment(\.horizontalSizeClass) var _horizontalSizeClass
    var verticalSizeClass: UserInterfaceSizeClass? { _verticalSizeClass }
    var horizontalSizeClass: UserInterfaceSizeClass? { _horizontalSizeClass }
    
    var body: some View {
        if(self.isPadLandscape){
            Text("iPad Landscape")
        }else if(self.isPadPortrait){
            Text("iPad Portrait")
        }else if(self.isPortrait){
            Text("iPhone Portrait")
        }else if(self.isLandscape){
            Text("iPhone Landscape")
        }
    }
}

The Extension:

protocol SizeClassAdjustable {
    var verticalSizeClass: UserInterfaceSizeClass? { get }
    var horizontalSizeClass: UserInterfaceSizeClass? { get }
}
extension SizeClassAdjustable {
    
    var isPad: Bool {
        return horizontalSizeClass == .regular && verticalSizeClass == .regular
    }
    var isPadLandscape: Bool {
        isPad && UIDevice.current.orientation.isLandscape
    }
    var isPadPortrait: Bool {
        isPad && UIDevice.current.orientation.isPortrait
    }
    var isPadOrLandscapeMax: Bool {
        horizontalSizeClass == .regular
    }
    var isLandscapeMax: Bool {
        horizontalSizeClass == .regular && verticalSizeClass == .compact
    }
    var isLandscape: Bool {
        verticalSizeClass == .compact
    }
    var isPortrait: Bool {
        verticalSizeClass == .regular
    }
}

Upvotes: 0

Views: 395

Answers (1)

Federica Benacquista
Federica Benacquista

Reputation: 843

Check if the deices are in portrait or landscape mode like this:

let screen = UIScreen.main.bounds

if UIDevice.current.userInterfaceIdiom == .phone{ //Phone

    if screen.width < screen.height { //Portrait
    } else { //Landscape
    }

} else { //iPad

    if screen.width < screen.height { //Portrait
    } else { //Landscape
    }

}

Then perform your actions in the proper scope.
Remember to import UIKit to use this method.

Upvotes: 1

Related Questions