user3847113 user3847113 - 7 months ago 111
Swift Question

UIView frame not updating after orientation change

How to detect orientation change after it happened using Swift 3?

I need to detect it after change to calculate frame size.


I asked this question because I need to redraw view on orientation change like in this question: Can't get background gradient to fill entire screen upon rotation

I don't know how to implement answer that is marked as a correct answer.

I tried another answer

self.backgroundImageView.layer.sublayers?.first?.frame = self.view.bounds

but it's not working.

I have

let color1 = UIColor(red: 225.0/255.0, green: 210.0/255.0, blue: 0.0/255.0, alpha: 1.0).cgColor
let color2 = UIColor(red: 255.0/255.0, green: 125.0/255.0, blue: 77.0/255.0, alpha: 1.0).cgColor

let gradientLayer = CAGradientLayer()
gradientLayer.colors = [color1, color2]
gradientLayer.locations = [ 0.0, 1.0]
gradientLayer.frame = self.view.bounds

self.view.layer.insertSublayer(gradientLayer, at: 0)


The above accepted answer returns frame size before transition.So your view is not updating..You need to get the frame size after the transition has been completed.

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {

        coordinator.animate(alongsideTransition: { (UIViewControllerTransitionCoordinatorContext) -> Void in

            let orient = UIApplication.shared.statusBarOrientation

            switch orient {

            case .portrait:


            case .landscapeLeft,.landscapeRight :



                print("Anything But Portrait")

            }, completion: { (UIViewControllerTransitionCoordinatorContext) -> Void in
                //refresh view once rotation is completed not in will transition as it returns incorrect frame size.Refresh here           

        super.viewWillTransition(to: size, with: coordinator)