我想將幾個按鈕堆疊在一起,然後顯示/隱藏它們作爲切換方式。 (想象一下視頻播放器中的播放/暫停/重放按鈕)。iOS:使用NSLayoutConstraint將對象堆疊在彼此的頂部
是否可以使用NSLayoutConstraint來做到這一點?
另外,也許有更好的方法來在iOS中創建多狀態按鈕?
這裏是我試過,但obvoiusly因爲這使他們旁邊的海誓山盟不起作用:
NSArray *constraints = [NSLayoutConstraint
constraintsWithVisualFormat:@"|[_playButton][_pauseButton][_replayButton][_scrubber][_minimizeButton]|"
options:0
metrics:nil
views:viewsDictionary];
使用從下面@dasdom一些技巧,我已經想出了以下內容:
NSArray *constraints = [NSLayoutConstraint
constraintsWithVisualFormat:@"|[_pauseButton]-[_scrubber]-[_minimizeButton]|"
options:NSLayoutFormatAlignAllCenterY
metrics:nil
views:viewsDictionary];
[constraints arrayByAddingObjectsFromArray:[NSLayoutConstraint
constraintsWithVisualFormat:@"|[_playButton]"
options:NSLayoutFormatAlignAllCenterY
metrics:nil
views:viewsDictionary]];
[constraints arrayByAddingObjectsFromArray:[NSLayoutConstraint
constraintsWithVisualFormat:@"|[_replayButton]"
options:NSLayoutFormatAlignAllCenterY
metrics:nil
views:viewsDictionary]];
[self addConstraints:constraints];
這是非常接近的 - 水平間距是正確的,對於第一條規則中的項目(pauseButton,scrubber,最小化),它們垂直對齊,但播放和重放按鈕太高...如果後續的NSLayoutFormatAlignAllCenterY
被忽略。
EDIT2:這裏是我結束了最後的代碼,花了比我想象的還要多得多,但似乎運作良好:
NSDictionary *metrics = @{
@"buttonPadding": @(kBarPaddingX)
};
// Align along Y center and set order, so scrubber stretches in the middle.
NSString *controlsVisualFormat =
@"|-buttonPadding-[_playButton]-[_scrubber]-[_minimizeButton]-buttonPadding-|";
NSArray *constraints = [NSLayoutConstraint
constraintsWithVisualFormat:controlsVisualFormat
options:NSLayoutFormatAlignAllCenterY
metrics:metrics
views:viewsDictionary];
// Set alignment of pauseButton and replayButton
constraints = [constraints arrayByAddingObjectsFromArray:[NSLayoutConstraint
constraintsWithVisualFormat:@"|-buttonPadding-[_pauseButton]"
options:NSLayoutFormatAlignAllCenterY
metrics:metrics
views:viewsDictionary]];
constraints = [constraints arrayByAddingObjectsFromArray:[NSLayoutConstraint
constraintsWithVisualFormat:@"|-buttonPadding-[_replayButton]"
options:NSLayoutFormatAlignAllCenterY
metrics:metrics
views:viewsDictionary]];
// Not sure why using NSLayoutFormatAlignAllCenterY above doesn't center the buttons vertically,
// so we need another set of constraints to center them vertically.
constraints = [constraints arrayByAddingObject:
[NSLayoutConstraint constraintWithItem:_pauseButton
attribute:NSLayoutAttributeCenterY
relatedBy:NSLayoutRelationEqual
toItem:_pauseButton.superview
attribute:NSLayoutAttributeCenterY
multiplier:1.0f
constant:0]];
constraints = [constraints arrayByAddingObject:
[NSLayoutConstraint constraintWithItem:_replayButton
attribute:NSLayoutAttributeCenterY
relatedBy:NSLayoutRelationEqual
toItem:_replayButton.superview
attribute:NSLayoutAttributeCenterY
multiplier:1.0f
constant:0]];
我知道你已經接受了一個答案,但你確定你的佈局不含糊嗎?在viewDidAppear中設置一個斷點,然後在調試器中剪切並粘貼以下內容:po [[UIWindow keyWindow] _autolayoutTrace]。 – bilobatum
是的,任何想法如何解決它? – Geoff
你需要在'contraintsWithVisualFormat'前加入'H:'和'V:'嗎? – ansible