[英]UIDynamics and Autolayout
Recently I used UIDynamics to animate an image view into place. 最近我使用UIDynamics将图像视图设置为动画。 However, because its autolayout y-pos constraint was set to off-screen, when navigating away from the screen and then returning to it, my image view was being placed off-screen again.
但是,因为它的自动布局y-pos约束被设置为屏幕外,当从屏幕导航然后返回到它时,我的图像视图再次被放置在屏幕外。 The animation took about 3 seconds, so after three seconds I just reset the constraint.
动画花了大约3秒钟,所以三秒后我就重置了约束。 That feels a little hacky.
这感觉有点hacky。
So my question is this: what is the proper way to handle autolayout and UIDynamics at the same time? 所以我的问题是:同时处理自动布局和UIDynamics的正确方法是什么?
This is not really a dynamics problem. 这不是一个真正的动态问题。 Autolayout is incompatible with any view animation, or any manual setting of the frame: when layout comes along, it is the constraints that will be obeyed.
Autolayout与任何视图动画或框架的任何手动设置都不兼容:当布局出现时,它将遵循约束条件 。 It is up to you, if you move a view manually in any way, to update the constraints to match its new position/size/whatever.
如果您以任何方式手动移动视图,更新约束以匹配其新位置/大小/等等,由您决定。
Having said that: with UIKit Dynamics, when the animation ends, the animator will pause, and the animator's delegate is notified: 话虽如此:使用UIKit Dynamics,当动画结束时,动画师将暂停,并通知动画师的代表:
https://developer.apple.com/library/ios/documentation/uikit/reference/UIDynamicAnimatorDelegate_Protocol/Reference/Reference.html#//apple_ref/occ/intfm/UIDynamicAnimatorDelegate/dynamicAnimatorDidPause : https://developer.apple.com/library/ios/documentation/uikit/reference/UIDynamicAnimatorDelegate_Protocol/Reference/Reference.html#//apple_ref/occ/intfm/UIDynamicAnimatorDelegate/dynamicAnimatorDidPause :
So that is the moment to update the constraints. 所以这是更新约束的时刻。
You have a nice solution provided by Geppy Parziale in this tutorial . 在本教程中 ,Geppy Parziale提供了一个很好的解决方案。
Basically you can create an object that conforms to UIDynamicItem: 基本上,您可以创建符合UIDynamicItem的对象:
@interface DynamicHub : NSObject <UIDynamicItem>
@property(nonatomic, readonly) CGRect bounds;
@property(nonatomic, readwrite) CGPoint center;
@property(nonatomic, readwrite) CGAffineTransform transform;
@end
That needs to init the bounds or it will crash: 这需要初始化边界或它将崩溃:
- (id)init {
self = [super init];
if (self) {
_bounds = CGRectMake(0, 0, 100, 100);
}
return self;
}
And then you use UIDynamics on that object and use the intermediate values to update your constraints: 然后在该对象上使用UIDynamics并使用中间值来更新约束:
DynamicHub *dynamicHub = [[DynamicHub alloc] init];
UISnapBehavior *snapBehavior = [[UISnapBehavior alloc] initWithItem:dynamicHub
snapToPoint:CGPointMake(50.0, 150.0)];
[snapBehavior setDamping:.1];
snapBehavior.action = ^{
self.firstConstraint.constant = [dynamicHub center].y;
self.secondConstraint.constant = [dynamicHub center].x;
};
[self.animator addBehavior:snapBehavior];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.