Skip to content

Instantly share code, notes, and snippets.

@mattyoung
Last active August 23, 2020 20:40
Show Gist options
  • Save mattyoung/c64cfb1db5d3e6d342d39814b113b6e9 to your computer and use it in GitHub Desktop.
Save mattyoung/c64cfb1db5d3e6d342d39814b113b6e9 to your computer and use it in GitHub Desktop.
import SwiftUI
struct ContentView: View {
let orientationNotification = NotificationCenter.default
.publisher(for: UIDevice.orientationDidChangeNotification)
.map { _ in
UIDevice.current.orientation
}
// .onReceive() mutate this @State var to trigger re-render on orientation change
@State var isPortrait = UIDevice.current.orientation.isPortrait
// hard code the text view height for demo purpose, query the text view to get its actual height
// using .preference()
static private let textHeight: CGFloat = 40
// There seems to be a layout "bug" in portrait orientation: the Image inside the ZStack (or VStack)
// cause everything to shift to the right.
var body: some View {
ZStack {
Image("Image")
.resizable()
.aspectRatio(contentMode: .fill)
// do this way to have something diff'ed on isPortrait variable to force re-rendering
Text(isPortrait ? "hello world" : "hello world")
.foregroundColor(.red)
.frame(maxWidth: .infinity, maxHeight: Self.textHeight)
.background(Color.white)
.offset(y: UIScreen.main.bounds.size.height / 2 - Self.textHeight)
}
.onReceive(orientationNotification) { _ in isPortrait = UIDevice.current.orientation.isPortrait }
.ignoresSafeArea()
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment