【问题标题】:UIView (without controller) : get notified when self disappearsUIView(无控制器):当自我消失时得到通知
【发布时间】:2014-07-16 08:31:59
【问题描述】:

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

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

@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

【问题讨论】:

    标签: ios iphone objective-c animation uiview


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

      希望对你有所帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-03-05
        • 1970-01-01
        • 1970-01-01
        • 2018-11-01
        • 1970-01-01
        • 1970-01-01
        • 2016-10-11
        • 2021-11-12
        相关资源
        最近更新 更多