[英]Changing element left, top, width and height constraints at runtime
出於我要創建的框架的目的,我需要設置UIView對象的frame屬性,但是當AutoLayout啟用時,我不能這樣做。 我的想法是,我可以從UIView對象中刪除所有布局約束,然后根據想要的框架創建新的約束。
因此,這就是我所擁有的,但無法正常工作(以下)。
//Remove current constraints
[self.view removeConstraints:self.view.constraints];
//create x constraint based on new x value
NSLayoutConstraint *xConstraint =[NSLayoutConstraint
constraintWithItem:self.view
attribute:NSLayoutAttributeLeft
relatedBy:NSLayoutRelationEqual
toItem:self.view.superview
attribute:NSLayoutAttributeLeft
multiplier:1.0
constant:self.x];
// add new x constrain
[self.view.superview addConstraint:xConstraint];
//create y constraint based on new y value
NSLayoutConstraint *yConstraint =[NSLayoutConstraint
constraintWithItem:self.view
attribute:NSLayoutAttributeTop
relatedBy:NSLayoutRelationEqual
toItem:self.view.superview
attribute:NSLayoutAttributeTop
multiplier:1.0
constant:self.y];
[self.view.superview addConstraint:yConstraint];
//create width constraint based on new width value
NSLayoutConstraint *widthConstraint =[NSLayoutConstraint
constraintWithItem:self.view
attribute:NSLayoutAttributeWidth
relatedBy:NSLayoutRelationEqual
toItem:nil
attribute:NSLayoutAttributeWidth
multiplier:1.0
constant:self.width];
[self.view.superview addConstraint:widthConstraint];
//create height constraint based on new height value
NSLayoutConstraint *heightConstraint =[NSLayoutConstraint
constraintWithItem:self.view
attribute:NSLayoutAttributeHeight
relatedBy:NSLayoutRelationEqual
toItem:nil
attribute:NSLayoutAttributeHeight
multiplier:1.0
constant:self.height];
[self.view.superview addConstraint:heightConstraint];
這是在運行時發生的情況:
編輯
更改后[self.view addConstraint:heightConstraint];
到[self.view.superview addConstraint:heightConstraint];
元素顯示,但我在控制台中收到以下消息
錯誤
以下列表中至少有一個約束是您不想要的約束。 嘗試以下操作:(1)查看每個約束,並嘗試找出不期望的約束; (2)查找添加了一個或多個不必要約束的代碼並進行修復。 (注意:如果看到的是您不了解的NSAutoresizingMaskLayoutConstraints,請參閱有關UIView屬性translationsAutoresizingMaskIntoConstraints的文檔)
(
"<NSLayoutConstraint:0x91475c0 H:|-(1)-[UIButton:0x728ab00](LTR) (Names: '|':UIScrollView:0x72845b0 )>",
"<NSLayoutConstraint:0x729dad0 H:|-(25)-[UIImageView:0x7284920](LTR) (Names: '|':UIScrollView:0x72845b0 )>",
"<NSLayoutConstraint:0x72924d0 UIButton:0x728ab00.leading == UIImageView:0x7284920.leading>"
)
您的問題是您正在向self.view添加一個引用self.view.superview的約束。 這將不起作用,這是您看到“約束是否從視圖的子樹外部引用某些東西的原因?這是非法的。”
您到底想做什么? 對於這個問題必須有另一種方法。 可能您可以將約束添加到超級視圖中,但我不確定您的情況。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.