TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

SOLVED: Get safeFrame width on rotate

Forums > SwiftUI

New to SwiftUI and have a beginners question. Need to send safeFrame width to a webview but struggle to get it to update correctly when rotating the phone.

I use this code in the body

        .onAppear() {
            let window = UIApplication.shared.windows[0]
            let safeFrame = window.safeAreaLayoutGuide.layoutFrame
            screenWidth = Int(safeFrame.width - 20)
        }
        .onRotate { newOrientation in
            let window = UIApplication.shared.windows[0]
            let safeFrame = window.safeAreaLayoutGuide.layoutFrame
            screenWidth = Int(safeFrame.height - 20)
        }

Together with this:

struct DeviceRotationViewModifier: ViewModifier {
    let action: (UIDeviceOrientation) -> Void

    func body(content: Content) -> some View {
        content
            .onAppear()
            .onReceive(NotificationCenter.default.publisher(for: UIDevice.orientationDidChangeNotification)) { _ in
                action(UIDevice.current.orientation)
            }
    }
}

// A View wrapper to make the modifier easier to use
extension View {
    func onRotate(perform action: @escaping (UIDeviceOrientation) -> Void) -> some View {
        self.modifier(DeviceRotationViewModifier(action: action))
    }
}

So, I use safeFrame.height because it seems like it reads values from before it gets a new orientation. However, it also seems like onRotate executes also when tilting the phone. I know, this is not a nice solution. Would be so much better if I could get the safeFrame width from the new orientation. Please give some ideas how I should code this instead.

1      

Solved this by using GeometryReader instead and its' .size.width-value.

1      

Hacking with Swift is sponsored by Blaze.

SPONSORED Still waiting on your CI build? Speed it up ~3x with Blaze - change one line, pay less, keep your existing GitHub workflows. First 25 HWS readers to use code HACKING at checkout get 50% off the first year. Try it now for free!

Reserve your spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.