user3847113 user3847113 - 1 month ago 10
Swift Question

Detect orientation change after it happened

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)

Answer

Add this function and you´ll detect the orientation change:

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    if UIDevice.current.orientation.isLandscape {
        print("Landscape")
    } else if UIDevice.current.orientation.isPortrait {
        print("Portrait")
    }
}