![](/img/trans.png)
[英]How to test a UILabel on a programatically added UIView with XCTest
[英]How to update constraint of a UILabel programatically
我在stroyboard中創建了一個UILabel
,其框架是(15, 55, 250, 20)
15,55,250,20 (15, 55, 250, 20)
。 根據我的要求,我想通過編碼將標簽框架更改為(15, 10, 250, 20)
。 但是對該標簽沒有任何影響。
所以我通過以下編碼更新約束:
mylabel.frame = CGRectMake(15, 10, 250, 20);
[mylabel needsUpdateConstraints];
但它不起作用。 請有人幫助我。 我在最近2天堅持這個。
我通過故事板添加這些約束
使用AutoLayout更新幀不起作用。 相反,創建約束並設置動畫。
以下是如何創建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)
如果要為寬度和高度創建約束,請記住將toItem
更改為nil
並將attribute
更改為NSLayoutAttribute.NotAnAttribute
。
如果要為約束設置動畫,只需更改它的constant
:
myConstraint.constant = 15
self.view.layoutIfNeeded()
首先,您應該將一個約束刪除到屏幕的右邊緣(45); 你過度約束你的觀點了。
當您想要更改在故事板中創建的約束時,您應該為它創建一個IBOutlet,並在代碼中修改其常量值。 由於你想要改變y位置,建立一個垂直間距約束(10個)的出口,我將這個例子稱為yCon。 你只需要這樣做,
self.yCon.constant = 55;
[self.view layoutIfNeeded];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.