4

I've set the constraints in IB as IBOutlet in the corresponding view controller. The values for such constraints that I set in IB and the storyboard are for portrait orientation. I need to change those constraints when the device changes to landscape orientation, and to restore them when rorating again to portrait.

I've read several posts regarding updating constrains when rotating the device but each of them say different things, and I don't understand which the process and method calls should be... I've been searching in Apple's documentation regarding Autolayout but I didn't find anything of how to programmatically change the constraints when rotating the device.

I know few things about autolayout and I'm really lost with this... I'd appreciate some clear explanation of how should I manage this scenario.

Thanks in advance

AppsDev
  • 12,319
  • 23
  • 93
  • 186

2 Answers2

3

UIViewController receives several orientation related calls triggered by the UIDevice notification if the view controller is part of the controller hierarchy managed by a window.

So Basically you have to override the method and update the autolayout constraint there.

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    if UIDevice.current.orientation.isLandscape {
        // Landscape
        constraintName.constant = 20.0  // constraintName will be your IBoutlet Constraint
    } else {
        // Portrait
        constraintName.constant = 100.0 // constraintName will be your IBoutlet Constraint
    }
}

Hope it will solve your problem.

Muhammad Waqas Bhati
  • 2,775
  • 20
  • 25
-3

I believe, that Size Classes in Interface Builder is the best way to achieve your goal:

Link to good tutorial

Link to Apple's official docs

Vitalii Gozhenko
  • 9,220
  • 2
  • 48
  • 66
  • Thanks again. The point is I need to support iOS 7 and above for iPhone devices and I already have a storyboard with only autolayout enabled. I have around 32 scenes in this storyboard... Is it worth to move to size classes at this point, and taking into account that I have to support iOS 7? – AppsDev Nov 09 '15 at 06:41
  • @AppsDev Move to size class support just mean change some particular constraint for some screens for some size class. You don't need to rewrite all constraints, and that is great :-) About support iOS7 - statistic will help you to decide: https://david-smith.org/iosversionstats/ and https://mixpanel.com/trends/#report/ios_9 – Vitalii Gozhenko Nov 09 '15 at 15:51
  • Thanks. About supporting iOS 7, I know it is not currently worth, but it is a requirement I was given... – AppsDev Nov 10 '15 at 06:28