[英]Is there a way to add an identifier to Auto Layout Constraints in Interface Builder?
在Interface Builder中進行了一些可視化布局后,我創建了一些我想在運行時訪問的約束。 有沒有辦法在Interface Builder中標記或識別約束,以便以后查找它們?
我想要這樣做的原因是我需要根據視覺指定的約束執行一些計算。 我知道Apple提供了可視格式語言 ,我可以在控制器中以編程方式指定約束。 我寧願不使用這種方法,所以我不會失去IB的設計時反饋。
建立引用插座確實有效,但問題仍然存在。
更新:
正如BartłomiejSemańczyk在他的回答中所解釋的那樣,現在在屬性檢查器中可以看到NSLayoutConstraint
的標識符字段,因此不必自己公開該字段。 只需在“ 文檔大綱”視圖或“故事板”視圖中選擇約束,然后在右側的“ 屬性”檢查器中添加標識符。
早期答案:
是的,這可以做到。 NSLayoutConstraint
有一個名為identifier
的屬性,可以在Interface Builder中公開並分配。 為了演示這個,我創建了一個單視圖應用程序 ,它有一個紅色框的子視圖。 此子視圖有4個約束:寬度,高度,在容器中水平居中,在容器中垂直居中。 我通過執行以下操作給寬度約束標識符redBoxWidth
:
單擊“ 文檔布局視圖”中的寬度約束。 然后在“ 用戶定義的運行時屬性”下的“ 標識檢查器 ”中,單擊“ 密鑰路徑”下的“ +
”。 將keyPath更改為identifier ,將Type Boolean更改為String ,並將Value設置為redBoxWidth
。
然后在ViewDidLoad
,可以按名稱查找約束並更改其值:
class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() for subview in view.subviews as [UIView] { for constraint in subview.constraints() as [NSLayoutConstraint] { if constraint.identifier == "redBoxWidth" { constraint.constant = 300 } } } } }
只需添加@ vacawama的答案。 您可以編寫UIView
類別並使用簡單函數提取約束,而不是在需要查找約束的任何位置復制/粘貼循環:
.h文件:
#import <UIKit/UIKit.h>
@interface UIView (EasyAutolayout)
-(NSLayoutConstraint *)constraintForIdentifier:(NSString *)identifier;
@end
.m文件:
#import "UIView+EasyAutolayout.h"
@implementation UIView (EasyAutolayout)
-(NSLayoutConstraint *)constraintForIdentifier:(NSString *)identifier {
for (NSLayoutConstraint *constraint in self.constraints) {
if ([constraint.identifier isEqualToString:identifier]) {
return constraint;
}
}
return nil;
}
@end
獲取自動布局約束的IBOutlet。
在NSLayoutConstraint類中有一個名為constant的屬性。
例如,您已經從IB的任何視圖中獲取了IBOutlet的高度約束,並且您想要以編程方式更改它的高度,您需要做的就是:
constraint.constant = isMoreHeight ? height1 : height2;
執行此操作后,您需要更新superview的視圖層次結構中的所有其他視圖。 為此,您需要在下面寫一行:
[self setLayoutIfNeeded];
為了獲得更好的用戶體驗,您可以將此行放在動畫塊中,以獲得更平滑的過渡效果,
[UIView animateWithDuration:0.3f animations:^{
[self.view layoutIfNeeded];
}];
希望這可以幫助..
那這個呢:
if let myconstraint = self.view.constraints.filter( { $0.identifier == "myconstraintId" }).first {
// TODO: your code here...
}
我對OSX的兩分錢(之前的答案與UIKit有關......)
它也適用於OSX:
final private func getConstraintForButton(){
let constraints = self.myButton.constraints
for constraint in constraints {
if constraint.identifier == "redBoxWidth" {
constraint.constant = 300
break
}
}
}
注意:似乎不適用於自定義NSView,而是......
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.