Reputation: 10769
I have a UIView that I would like to center horizontally over the main view and then center vertically over the main view, minus about 14 pixels.
If I set it up with IB it works on the Retina 3.5, but when running on Retina 4 it is of course off by roughly 40 pixels.
I am thinking the best solution is establishing these constraints programmatically based on screen height?
Upvotes: 2
Views: 2664
Reputation: 439
You don't need to set constraints programmatically to align a view to horizontal & vertical center of the screen. It can be done via Interface builder itself. However, you still can set constraints using NSLayoutAnchor apis in code, like the below example. NSLayoutAnchor apis are simple, elegant and, concise. And are available since iOS 9.
myView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor)
myView.centerYAnchor.constraint(equalTo: self.view.centerYAnchor)
Upvotes: 1
Reputation: 104092
Use the centerX and centerY constants, and put in a constant of 14 (or -14 not sure which way you want it to be),
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.view attribute:NSLayoutAttributeCenterX relatedBy:0 toItem:view attribute:NSLayoutAttributeCenterX multiplier:1 constant:0]];
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.view attribute:NSLayoutAttributeCenterY relatedBy:0 toItem:view attribute:NSLayoutAttributeCenterY multiplier:1 constant:14]];
Upvotes: 10
Reputation: 4369
In order to make your view in Center(Horizontally & Vertically). Select the view in Interface Builder, then from Top Menu, Select Editor> Align> Horizontal Center in Container/ Vertical Center in Container.
You can also add more constraints to satisfy view's Geometry.
Upvotes: 1