Quantcast
Channel: XCode – Ryadel
Viewing all articles
Browse latest Browse all 8

Objective-C: Programmatically set UIView alignment without using Storyboard

$
0
0

I recently wrote an article about removing Storyboards constraints programmatically. When you do that, you’ll often also want to replace the removed constraints with new ones: you can do that – programmatically as well – by using the addConstraint method, which allows to set one or more constraints between any two UIView items.

Let’s see some example by taking a standard UIButton item as the first object and its Parent View (or superview, as it is called by Objective-C) as the second one.

How to align an object to its ParentView Center X / Center Y

parent.center.x.center.y
Center X, Center Y

 

[self.btn.superview addConstraint:[NSLayoutConstraint
        constraintWithItem:self.btn.superview
        attribute:NSLayoutAttributeCenterX
        relatedBy:NSLayoutRelationEqual
        toItem:self.btn
        attribute:NSLayoutAttributeCenterX
        multiplier:1.0
        constant:0.0]];
    [self.btn.superview addConstraint:[NSLayoutConstraint
        constraintWithItem:self.btn.superview
        attribute:NSLayoutAttributeCenterY
        relatedBy:NSLayoutRelationEqual
        toItem:self.btn
        attribute:NSLayoutAttributeCenterY
        multiplier:1.0
        constant:0.0]];

 

How to align an object to its ParentView Center X / Top Y

parent.center.x.top.y
Center X, Top Y

 

[self.btn.superview addConstraint:[NSLayoutConstraint
        constraintWithItem:self.btn.superview
        attribute:NSLayoutAttributeCenterX
        relatedBy:NSLayoutRelationEqual
        toItem:self.btn
        attribute:NSLayoutAttributeCenterX
        multiplier:1.0
        constant:0.0]];
    [self.btn.superview addConstraint:[NSLayoutConstraint
        constraintWithItem:self.btn.superview
        attribute:NSLayoutAttributeTop
        relatedBy:NSLayoutRelationEqual
        toItem:self.btn
        attribute:NSLayoutAttributeTop
        multiplier:1.0
        constant:0.0]];

 

Align an object to its ParentView Left X / Top Y

parent.left.x.top.y
Left X, Top Y

[self.btn.superview addConstraint:[NSLayoutConstraint
        constraintWithItem:self.btn.superview
        attribute:NSLayoutAttributeLeft
        relatedBy:NSLayoutRelationEqual
        toItem:self.btn
        attribute:NSLayoutAttributeLeft
        multiplier:1.0
        constant:0.0]];
    [self.btn.superview addConstraint:[NSLayoutConstraint
        constraintWithItem:self.btn.superview
        attribute:NSLayoutAttributeTop
        relatedBy:NSLayoutRelationEqual
        toItem:self.btn
        attribute:NSLayoutAttributeTop
        multiplier:1.0
        constant:0.0]];

 

I think you got it.

Happy coding!

 

The post Objective-C: Programmatically set UIView alignment without using Storyboard appeared first on Ryadel.


Viewing all articles
Browse latest Browse all 8

Trending Articles