如果您將添加額外的巨大視圖D,該怎麼辦? D將覆蓋(A和B)視圖。你應該這樣做
- 創建d
- C.removeFromSuperview()
- 到d將C與約束,這將代替c在同一地點爲A
- 變化約束上的中心(C應該移動到B的中心動畫)從d
- 刪除C和它添加到B(C的更新約束)
像這樣
- (IBAction)MAGIC:(id)sender
{
UIView* view = [[UIView alloc] initWithFrame:self.view.bounds];
view.backgroundColor = [UIColor clearColor];
[self.view addSubview:view];
CGRect fromRect = [self.top convertRect:self.white.frame toView:view];
[self.white removeFromSuperview];
[view addSubview:self.white];
NSLayoutConstraint* topConstraint = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-(top)-[_white]"
options:0
metrics:@{@"top":@(CGRectGetMinY(fromRect))}
views:NSDictionaryOfVariableBindings(_white)].lastObject;
NSLayoutConstraint* leftConstraint = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-(left)-[_white]"
options:0
metrics:@{@"left":@(CGRectGetMinX(fromRect))}
views:NSDictionaryOfVariableBindings(_white)].lastObject;
[view addConstraints:@[topConstraint, leftConstraint]];
CGRect bottomViewFrameInView = [self.bottom convertRect:self.bottom.bounds toView:view];
[view layoutIfNeeded];
topConstraint.constant = CGRectGetMidY(bottomViewFrameInView) - CGRectGetHeight(self.white.bounds)/2;
leftConstraint.constant = CGRectGetMidX(bottomViewFrameInView) - CGRectGetWidth(self.white.bounds)/2;
[UIView animateWithDuration:0.5
animations:^{
[view layoutIfNeeded];
}
completion:^(BOOL finished) {
[self.white removeFromSuperview];
[self.bottom addSubview:self.white];
NSLayoutConstraint* topConstraint = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-(top)-[_white]"
options:0
metrics:@{@"top":@(CGRectGetMidY(self.bottom.bounds) - CGRectGetHeight(self.white.bounds)/2)}
views:NSDictionaryOfVariableBindings(_white)].lastObject;
NSLayoutConstraint* leftConstraint = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-(left)-[_white]"
options:0
metrics:@{@"left":@(CGRectGetMidX(self.bottom.bounds) - CGRectGetWidth(self.white.bounds)/2)}
views:NSDictionaryOfVariableBindings(_white)].lastObject;
[self.bottom addConstraints:@[topConstraint, leftConstraint]];
[view removeFromSuperview];
}];
}

來源
2015-10-13 14:17:38
Che
我不調用'現在右layoutIfNeeded';它似乎正確地更新。就像我說的那樣,現在整個事情都在一個動畫塊中,但是因爲我認爲它失敗了,因爲我沒有激活約束 - 我從字面上添加新的約束,因爲當視圖從其中移除時,以前的會丟失上海華。 – FizzBuzz
問題在於你沒有調用layoutifededed,並且系統在系統在您的更新之後下一次繪製視圖之前執行它,並且系統在沒有動畫的情況下執行它,請嘗試使用layoutIfNeeded動畫。 – ogres
謝謝;我剛剛嘗試過,它似乎仍在跳躍。不過,如果我將它設置爲偏離中心的偏移量(例如多個0.9),它會直接跳到中心,然後將其設置爲0.9。 – FizzBuzz