滑入一个 UIButton 并在达到一定距离时按下另一个 UIButton

Slide in an UIButton and push other UIButton when a certain distance is reached

我想从左向右滑入一个 UIButton(屏幕截图中的灰色)并将其置于屏幕中央。虽然已经有一个 UIButton(屏幕截图中的橙色)居中,但应将此按钮推到右侧,并且始终与滑入的 UIButton 保持 20 的距离。

居中按钮(橙色)有四个约束:

当前将滑入的按钮(灰色)有以下限制:

我的想法是为灰色 UIButton 的 "leading space" 约束添加一个出口,并使用 UIView 的 animateWithDuration:animations: 方法对其进行动画处理:

- (void)viewDidLoad {
    [super viewDidLoad];

    self.slideInLeadingConstraint.constant = 100;
    [self.slideInButton setNeedsUpdateConstraints];
    [UIView animateWithDuration:3.0 animations:^{
        [self.slideInButton layoutIfNeeded];
        [self.centerButton layoutIfNeeded];
    }];
}

为了使它起作用,我可以更改约束条件中的哪些内容?

  1. 由于您希望橙色按钮在某个点移动,因此您不能强制它居中。将优先级从 1000 降低到更低。这意味着:我真的希望它居中,但不一定非得居中。

  2. 在两个按钮之间添加水平距离(leading/trailing)约束。将其值设置为 >= 20。这意味着:距离不能低于 20pt,但任何更大的都可以。

  3. 动画消失 ;)
    在您的动画块中,您需要对动画中涉及的所有视图或它们的公共超级视图之一调用 layoutIfNeeded

Note:
The reason why you had problems with this is that you have called it from viewDidLoad. At that point, the view has been fully initialized, but not added to the hierarchy yet.
It's not yet certain, how big the parent view will be and dimensions for the animation will have to be guessed (by just taking the dimensions of your scene in the storyboard).
Performing the animation after it has been initially displayed (e.g. in viewDidAppear) causes the animation to be calculated with the right dimensions.