I am creating a UILabel
in stroyboard which frame is (15, 55, 250, 20)
. According to my requirement I want to change that label frame to (15, 10, 250, 20)
through coding. But there is no affect on that label.
So I update constraint through coding like below:
mylabel.frame = CGRectMake(15, 10, 250, 20);
[mylabel needsUpdateConstraints];
But it's not working. Please anybody help me. I am stuck on this from last 2 days.
I am adding these constraint through storyboard
Updating frames does not work well with AutoLayout. Create and animate constraints instead.
Here's how you can create a NSLayoutConstraint
and add it to the view:
var myLabelConstraint = NSLayoutConstraint (item: myLabel,
attribute: NSLayoutAttribute.Top, // You can also choose Width, Height, Bottom, Leading, Trailing
relatedBy: NSLayoutRelation.Equal,
toItem: self.view
attribute: NSLayoutAttribute.Top,
multiplier: 1,
constant: 10)
self.view.addConstraint(myLabelConstraint)
If you are creating a constraint for width and height, remember to change toItem
into nil
and attribute
into NSLayoutAttribute.NotAnAttribute
.
If you want to animate a constraint just change the constant
of it:
myConstraint.constant = 15
self.view.layoutIfNeeded()
First, you should delete the one constraint to the right edge of the screen (45); you're over constraining your view.
When you want to change a constraint you made in the storyboard, you should make an IBOutlet to it, and modify its constant value in code. Since you want to change the y position, make an outlet to the vertical spacing constraint (the 10 one), I'll call it yCon for this example. You only need to do this,
self.yCon.constant = 55;
[self.view layoutIfNeeded];
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.