我可能會建議一種不同的方法來近似UISnapBehavior
,但是避免試圖與UIKit Dynamics結合使用自動佈局,而您依靠自動佈局引擎來確定視圖的最終位置。 (顯然,如果你知道最終目的地,那麼你只是暫停自動佈局,捕捉,當捕捉完成時,你會應用約束。)
對於視圖捕捉到的彈跳效果的地方,你可以使用animateWithDuration
與usingSpringWithDamping
參數,如:
// create the view
UIView *view = ...;
view.translatesAutoresizingMaskIntoConstraints = NO;
[self.view addSubview:view];
// add all of the constraints for the final position
NSDictionary *views = NSDictionaryOfVariableBindings(view);
[self.view addConstraints:...];
// animate the application of those constraints with low `withSpringWithDamping`
[UIView animateWithDuration:1.0 delay:0.0 usingSpringWithDamping:0.5 initialSpringVelocity:0.0 options:0 animations:^{
[view layoutIfNeeded];
} completion:nil];
如果您還想要一些旋轉,因爲它卡入到位,您可以使用animateKeyframesWithDuration
:
[UIView animateKeyframesWithDuration:1.0 delay:0.0 options:0 animations:^{
[UIView addKeyframeWithRelativeStartTime:0.0 relativeDuration:0.5 animations:^{
view.transform = CGAffineTransformMakeRotation(M_PI_4/2);
}];
[UIView addKeyframeWithRelativeStartTime:0.5 relativeDuration:0.25 animations:^{
view.transform = CGAffineTransformMakeRotation(-M_PI_4/4);
}];
[UIView addKeyframeWithRelativeStartTime:0.75 relativeDuration:0.125 animations:^{
view.transform = CGAffineTransformMakeRotation(M_PI_4/16);
}];
[UIView addKeyframeWithRelativeStartTime:0.875 relativeDuration:0.125 animations:^{
view.transform = CGAffineTransformMakeRotation(0);
}];
} completion:nil];
這不正是UISnapBehavior
,但近似接近。您可以在關鍵幀動畫的旋轉時間和旋轉量以及彈簧阻尼係數方面盡情發揮。但是,這說明了一種使用基於塊的動畫獲取類似於快照的行爲的方法。
來源
2014-11-14 19:53:30
Rob
實際上,您並不需要禁用視圖上的約束,以便將UIKitDynamics與自動佈局配合使用。前段時間有人向我展示了一個簡單的技巧,如果您創建的自定義NSObject不符合,請向此自定義項添加行爲,然後更改行爲的操作塊中的約束。 –
DBoyer
2014-10-09 06:25:33
這是正確的答案,動畫的約束,而不是框架。 – Gusutafu 2014-11-02 02:33:18