简体   繁体   English

如何以编程方式更新UILabel的约束

[英]How to update constraint of a UILabel programatically

I am creating a UILabel in stroyboard which frame is (15, 55, 250, 20) . 我在stroyboard中创建了一个UILabel ,其框架是(15, 55, 250, 20) 15,55,250,20 (15, 55, 250, 20) According to my requirement I want to change that label frame to (15, 10, 250, 20) through coding. 根据我的要求,我想通过编码将标签框架更改为(15, 10, 250, 20) 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. 我在最近2天坚持这个。

I am adding these constraint through storyboard 我通过故事板添加这些约束

在此输入图像描述

Updating frames does not work well with AutoLayout. 使用AutoLayout更新帧不起作用。 Create and animate constraints instead. 相反,创建约束并设置动画。

Here's how you can create a NSLayoutConstraint and add it to the view: 以下是如何创建NSLayoutConstraint并将其添加到视图中的方法:

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 . 如果要为宽度和高度创建约束,请记住将toItem更改为nil并将attribute更改为NSLayoutAttribute.NotAnAttribute

If you want to animate a constraint just change the constant of it: 如果要为约束设置动画,只需更改它的constant

myConstraint.constant = 15
self.view.layoutIfNeeded()

First, you should delete the one constraint to the right edge of the screen (45); 首先,您应该将一个约束删除到屏幕的右边缘(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. 当您想要更改在故事板中创建的约束时,您应该为它创建一个IBOutlet,并在代码中修改其常量值。 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. 由于你想要改变y位置,建立一个垂直间距约束(10个)的出口,我将这个例子称为yCon。 You only need to do this, 你只需要这样做,

self.yCon.constant = 55;
[self.view layoutIfNeeded];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM