Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIView frame not updating after orientation change

Tags:

ios

swift

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

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

EDIT

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.

In viewDidLoad() 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)
like image 262
user3847113 Avatar asked Oct 26 '16 12:10

user3847113


2 Answers

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:

                print("Portrait")

            case .landscapeLeft,.landscapeRight :

                print("Landscape")

            default:

                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)

    }
like image 124
Anish Parajuli 웃 Avatar answered Sep 18 '22 16:09

Anish Parajuli 웃


To get orientation change callback you need to add this Notification

NotificationCenter.default.addObserver(self, selector: #selector(ViewController.rotated), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)

and you need to implement this method

func rotated() {
    if(UIDeviceOrientationIsLandscape(UIDevice.current.orientation))
    {
        print("landscape")
    }

    if(UIDeviceOrientationIsPortrait(UIDevice.current.orientation))
    {
        print("Portrait")
    }
}
like image 23
Rajat Avatar answered Sep 21 '22 16:09

Rajat