[英]NSLayoutConstraint and “attach” two labels to each other
我有兩個標簽。 如果移動一個,我希望能夠移動它們。 如何將它們與NSLayoutConstraints“連接”在一起? 我可以在IB中執行此操作,但需要在代碼中執行此操作。
另外,什么是NSLayoutAttributeBaseline,NSLayoutAttributeLeading和NSLayoutAttributeTrailing?
編輯:
中心poweredByLabel(又名label02):
[constraints addObject:[NSLayoutConstraint constraintWithItem:poweredByLabel
attribute:NSLayoutAttributeCenterX
relatedBy:NSLayoutRelationEqual
toItem:myImage
attribute:NSLayoutAttributeCenterX
multiplier:1.0
constant:0]];
堆疊標簽並垂直切換:
[constraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[rememberPasswordSwitch]-10-[rememberPasswordLabel]-10-[versionLabel]-[poweredByLabel]-|"
options:NSLayoutFormatAlignAllBaseline
metrics:nil
views:viewsDictionary]];
產生錯誤:
*由於未捕獲的異常'NSInvalidArgumentException'終止應用程序,原因:'無法解析約束格式:選項掩碼要在垂直邊緣上對齊的視圖,這對於也是垂直的布局是不允許的。 五:[rememberPasswordSwitch] -10- [rememberPasswordLabel] -10- [versionLabel] - [poweredByLabel] - | ........................... .................................................. .............................. ^”
w / out NSLayoutFormatAlignAllBaseline選項,它運行正常(它們堆棧但不是全部水平居中)。
如果需要在代碼中執行此操作,請首先創建NSLayoutConstraint,然后將約束添加到標簽的superview。
有兩種方法可以在代碼中創建約束。 constraintsWithVisualFormat
通常比constraintWithItem
簡潔得多。
// Make label1's NSLayoutAttributeTrailing be the 'standard Aqua space' away from label2's NSLayoutAttributeLeading. Also, vertically align their baselines.
NSArray* constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"H:[label1]-[label2]" options:NSLayoutFormatAlignAllBaseline metrics:nil views:NSDictionaryOfVariableBindings(label1, label2) ] ;
然后將約束添加到標簽的superview:
[label1.superview addConstraints:constraints] ; // Use `label1.superview` or your own reference to the label's superview.
Cocoa自動布局指南簡短易懂。 給它一個閱讀,我很樂意回答你還有的任何問題。
編輯1
選項NSLayoutFormatAlignAllBaseline
創建約束(除了由NSLayoutFormatAlignAllBaseline
創建的約束),這些約束垂直對齊所有指定對象的基線。 如果您的VisualFormat字符串正在創建垂直約束(它以“V:”開頭),則您不想使用此選項。 您希望使用0(表示沒有選項)或創建水平約束的選項,如NSLayoutFormatAlignAllCenterX。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.