UIView(没有控制器):当自我消失时得到通知

时间:2014-07-16 08:31:59

标签: ios iphone objective-c animation uiview

我有一个没有任何关联的UIViewController的UIView,它不断地使用自动布局和layoutIfNeeded进行动画制作(参见下面的代码)。 但是当这个视图(包含在另一个视图中)消失时(例如当模态视图覆盖它所包含的视图时)并且在我关闭此模态视图后,动画视图不再是动画。

我设法使用didMoveToWindow:动画方法将其设置为动画,但我不确定这是否是正确的方法。

@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

2 个答案:

答案 0 :(得分:0)

您始终可以使用行为模式:KVO来控制UIView的状态或我要做什么,使用通知在您想要的时候为视图设置动画。这两个选项都有效。您也可以拥有与此类关联的委托,并在您的UIView中实现您想要的行为。

答案 1 :(得分:0)

假设您的视图包含在Controller中包含的另一个视图中,您可以设置一个名为didReturnFromModalChildView的BOOL变量,每次呈现该模态视图时都将其设置为true。当您关闭该模态视图时,您的应用程序将调用-(void)viewWillAppear:(BOOL)animated。在这里,您必须检查BOOL变量是否设置为Yes,然后使用公共方法调用,如果您有对要动画的视图的引用,或者委托进程或观察者通知模式。不要忘记将didReturnFromModalChildView设置为false。

我希望这会对你有所帮助。

相关问题