Reputation: 167
I'd like to change Text displayed based on device orientation. A visual will describe what I am trying to achieve better :)
Here is landscape mode
And here is portrait mode
I'd like to display a short format for the month name in portrait mode and have found various posts describing how to achieve this by detecting device orientation. I also found that this is not in the best practice category so wondering if there is a better way. Code is just a VStack with two Text components inside a ScrollView.
Upvotes: 1
Views: 2150
Reputation: 891
SwiftUI doesn't seem to have constraints, or constraint variants like the interface builder does for orientation. I don't think there is an established best practices for it yet. I wouldn't hesitate to use the orientation values until something comes out that allow us to better react to orientation changes.
I would probably do something like this to react to orientation:
[Updated with @kevin-renskers improvement]
struct ContentView: View {
@State var orientation: UIDeviceOrientation = UIDevice.current.orientation
var body: some View {
Text(orientation.isLandscape ? "Landscape" : "Portrait")
.onReceive(NotificationCenter.Publisher(center: .default, name: UIDevice.orientationDidChangeNotification)) { _ in
self.orientation = UIDevice.current.orientation
}
}
}
Upvotes: 8
Reputation: 5940
I would change the accepted answer a little bit to instead use .onReceive
:
.onReceive(NotificationCenter.Publisher(center: .default, name: UIDevice.orientationDidChangeNotification)) { _ in
self.orientation = UIDevice.current.orientation
}
This should handle unsubscribing automatically.
Upvotes: 8