通過手動定位做到這一點,你將計算爲按鈕像這樣的框架:
NSButton *button = [[NSButton alloc] initWithFrame:NSMakeRect(NSMaxX(self.bounds) - (100 * [_buttonIdentifierList count] + 10) - 70, 5, 70, 20)];
也就是說,你把你的電流計算這是一個向右側偏移(從左側邊緣)並取消它,使其向左偏移。您添加包含視圖的右邊緣的值,因此它是距右邊緣的偏移量。它計算了按鈕右邊緣的X位置,因此您可以減去該按鈕的寬度以獲取按鈕的原點,該按鈕位於其左邊緣。
要使用自動佈局(使用NSLayoutConstraint
),你可以這樣做:
NSButton *button = [[NSButton alloc] initWithFrame:NSZeroRect];
[button setTitle:title];
[button setAction:@selector(actionButtonPressed:)];
[button setTarget:self];
[button setIdentifier:identifier];
button.translatesAutoresizingMaskIntoConstraints = NO;
[self addSubview:button];
__block NSButton* previousButton = nil;
if (_buttonIdentifierList.count)
{
NSString* previousButtonIdentifier = _buttonIdentifierList.lastObject;
[self.subviews enumerateObjectsUsingBlock:^(NSView* subview, NSUInteger idx, BOOL *stop){
if ([subview.identifier isEqualToString:previousButtonIdentifier])
{
previousButton = (NSButton*)subview;
*stop = YES;
}
}];
}
NSDictionary* metrics = @{ @"buttonWidth": @70,
@"buttonHeight": @20,
@"buttonSeparation": @30,
@"horizontalMargin": @10,
@"verticalMargin": @5 };
if (previousButton)
{
NSDictionary* views = NSDictionaryOfVariableBindings(button, previousButton);
NSArray* constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"[button(buttonWidth)]-(buttonSeparation)-[previousButton]" options:NSLayoutFormatAlignAllBaseline metrics:metrics views:views];
[self addConstraints:constraints];
}
else
{
NSDictionary* views = NSDictionaryOfVariableBindings(button);
NSArray* constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"[button(buttonWidth)]-(horizontalMargin)-|" options:0 metrics:metrics views:views];
[self addConstraints:constraints];
constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:[button(buttonHeight)]-(verticalMargin)-|" options:0 metrics:metrics views:views];
[self addConstraints:constraints];
}
[_buttonIdentifierList addObject:identifier];
尋找previousButton
將被簡化,如果你跟蹤按鈕,而不是標識符。如果你有一個按鈕對象,很容易得到它的標識符,但是相反(獲取按鈕對象,當你擁有的只是標識符)並不那麼簡單。
如果你想讓按鈕成爲它們的自然寬度和高度,而不是一個固定值,那麼你可以忽略這些寬度/高度說明符(即使用[button]
而不是[button(buttonWidth)]
)。如果您希望所有按鈕具有相同的寬度,但讓系統選取自然寬度最大的按鈕的寬度,則可以使用[button(==previousButton)]
。由於按鈕的默認壓縮電阻優先級高於其內容擁抱優先級,因此會選擇不壓縮其中任何一個的最小寬度。
如果您希望按鈕距離彼此的標準距離而不是30點的固定值,則可以使用使用-
而不是-(buttonSeparation)-
。同樣,如果您希望它們成爲超視角邊緣的標準距離,則可以使用-
而不是-(horizontalMargin)-
或-(verticalMargin)-
。