0

Hi i am programmaticaly adding some views like this

        let xPos = (self.view.frame.size.width - 200)/2
        self.headerLabel = UILabel(frame: CGRect(x: xPos, y: 50.0, width: 200.0, height: 100.0))
        self.shopButton = UIButton(frame: CGRect(x: xPos, y: 150.0, width: 200.0, height: 40.0))
        self.createButton = UIButton(frame: CGRect(x: xPos, y: 230.0, width: 200.0, height: 40.0))
        self.orLabel = UILabel(frame: CGRect(x: xPos, y: 200.0, width: 200.0, height: 20.0))

problem is when I rotate device to the landscape mode and vice versa my views are aligned to the left side. How can I prevent it?

  • You can find some good documentation/post there : http://stackoverflow.com/questions/27473810/how-to-change-layout-constraints-programmatically-on-display-rotation and there https://developer.apple.com/library/content/documentation/UserExperience/Conceptual/AutolayoutPG/WorkingwithConstraintsinInterfaceBuidler.html –  Feb 27 '17 at 14:38

3 Answers3

0

Add constraints in your view to its super view using NSLayoutConstaint

For eg

let horizontalConstraint = NSLayoutConstraint.init(item: view, attribute: .centerX, relatedBy: .equal, toItem: view.superview, attribute: .centerX, multiplier: 1, constant: 1)
        horizontalConstraint.isActive = true

        let verticalConstraint = NSLayoutConstraint.init(item: view, attribute: .centerY, relatedBy: .equal, toItem: view.superview, attribute: .centerY, multiplier: 1, constant: 1)
        verticalConstraint.isActive = true
Chanchal Chauhan
  • 1,530
  • 13
  • 25
0

I would add these elements in the interface builder if you can. You can then manually set up your constraints, which is much easier than adding them programmatically. The reason you are seeing this behavior is because your elements have no constraints, so they do not change orientation when the screen is rotated.

Check out these links: https://developer.apple.com/library/content/documentation/UserExperience/Conceptual/AutolayoutPG/WorkingwithConstraintsinInterfaceBuidler.html

https://www.raywenderlich.com/115440/auto-layout-tutorial-in-ios-9-part-1-getting-started-2

tennis779
  • 338
  • 2
  • 6
  • 19
0

If you're working with no Storyboards at all I'd recommend using Neon framework. It helps you to design entire views - and also placing buttons, images,... on it - programmically.

See the following Github repo: https://github.com/mamaral/Neon

Florian Chrometz
  • 445
  • 2
  • 9
  • 22