0
votes

I want to apply different constraints (size, position, color, etc.) to a UIView (of a container view) when the user switches between portrait and landscape orientations.

For some reason, the initial screen height is not the Safe Area height - after rotating the screen it seems to be ok. What am I doing wrong???

"h = 667.0, w = 375.0" portrait

"h = 343.0, w = 667.0" landscape

"h = 603.0, w = 375.0" portrait

"h = 343.0, w = 667.0" landscape

"h = 603.0, w = 375.0" portrait

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    super.viewWillTransition(to: size, with: coordinator)
    coordinator.animate(alongsideTransition: nil) { (context) in
        self.setVC1Constraints()
    }
}

override func viewDidLoad() {
    super.viewDidLoad() 
    addChildVC1()
}

func addChildVC1() {
    addChild(childVC1)
    view.addSubview(childVC1.view)
    setVC1Constraints()
}


func setVC1Constraints() {
    let orientation = getScreenOrientation()
    
    let screenHeight = view.safeAreaLayoutGuide.layoutFrame.size.height
    let screenWidth = view.safeAreaLayoutGuide.layoutFrame.size.width

    print("h = \(screenHeight), w = \(screenWidth)")
    
    childVC1.view.translatesAutoresizingMaskIntoConstraints = false
    
    childVC1.view.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 0).isActive = true
    childVC1.view.leftAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leftAnchor, constant: 0).isActive = true

    
    if orientation == Orientations.Portrait || orientation == Orientations.PortraitUpsideDown {
        print("portrait")        }
        
    else if orientation == Orientations.LandscapeRight || orientation == Orientations.LandscapeLeft {
        print("landscape")        }
}
1

1 Answers

0
votes

This is the expected behavior, as you can see the gap is represented by the navigation bar height and quoting Apple docs:

safeAreaLayoutGuide

The layout guide representing the portion of your view that is unobscured by bars and other content.

When the view is visible onscreen, this guide reflects the portion of the view that is not covered by navigation bars, tab bars, toolbars, and other ancestor views.