Ios UIView(不带控制器):自我消失时收到通知
我有一个UIView,没有任何关联的UIViewController,它不断地使用自动布局和LayoutIfNeed设置动画(参见下面的代码)。 但是当这个视图(包含在另一个视图中)消失(例如,当一个模态视图覆盖了它所包含的视图时)并且我关闭了这个模态视图之后,动画视图就不再是动画了 我设法用didMoveToWindow:animated方法将其动画化,但我不确定这是正确的方法Ios UIView(不带控制器):自我消失时收到通知,ios,iphone,objective-c,animation,uiview,Ios,Iphone,Objective C,Animation,Uiview,我有一个UIView,没有任何关联的UIViewController,它不断地使用自动布局和LayoutIfNeed设置动画(参见下面的代码)。 但是当这个视图(包含在另一个视图中)消失(例如,当一个模态视图覆盖了它所包含的视图时)并且我关闭了这个模态视图之后,动画视图就不再是动画了 我设法用didMoveToWindow:animated方法将其动画化,但我不确定这是正确的方法 @interface AnimatingView() @property (strong, nonatomic) U
@interface AnimatingView()
@property (strong, nonatomic) UIView *aSubview;
@property (strong, nonatomic) NSLayoutConstraint *constraintTop;
@property (assign, nonatomic, getter = isStarted) BOOL started;
@property (assign, nonatomic) BOOL stopAnimation;
@end
@implementation AnimatingView
- (id)init
{
self = [super init];
if (self) {
self.stopAnimation = YES;
/* setting base auto layout constraints */
}
return self;
}
-(void)animate{
float aNewConstant = arc4random_uniform(self.frame.size.height);
[UIView animateWithDuration:ANIMATION_DURATION animations:^{
[self removeConstraint:self.constraintTop];
self.constraintTop = [NSLayoutConstraint constraintWithItem:self.aSubview attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeTop multiplier:1 constant:aNewConstant];
[self addConstraint:self.constraintTop];
[self layoutIfNeeded];
} completion:^(BOOL finished) {
if (finished && !self.stopAnimation) {
[self animate];
}
}];
}
- (void)didMoveToWindow{
[super didMoveToWindow];
if ([self isStarted]) {
[self stop];
[self start];
}
}
-(void)start{
if (![self isStarted]) {
self.stopAnimation = NO;
[self setStarted:YES];
[self animate];
}
}
-(void)stop{
if ([self isStarted]) {
self.stopAnimation = YES;
[self setStarted:NO];
}
}
@end
您可以始终使用行为模式:KVO来控制UIView的状态,或者在需要时使用通知来设置视图的动画。两个选项都有效。您还可以拥有一个与该类关联的委托,并在UIView中实现您想要的行为。假设您的视图包含在控制器中的另一个视图中,您可以设置一个名为
didReturnFromModalChildView
的BOOL变量,您可以在每次呈现该模式视图时将其设置为true。当您关闭该模式视图时,您的应用程序将调用-(void)view将显示:(BOOL)animated
。在这里,您必须检查BOOL变量是否设置为Yes,然后如果您有对要设置动画的视图、委托过程或观察者通知模式的引用,则使用公共方法调用。别忘了将didReturnFromModalChildView设置为false
我希望这对你有帮助