【问题标题】:How to know if view is being animated?如何知道视图是否正在动画?
【发布时间】:2014-06-12 22:05:08
【问题描述】:

有没有办法知道我的 setFrame: 的自定义实现(或可动画属性的其他设置器)是从动画块调用的,即它是动画还是直接设置?

例子:

- (void)setFrame:(CGRect)newFrame {
    [super setFrame:newFrame];
    BOOL willBeAnimated = ?????
    if (willBeAnimated) {
        // do something 
    } else {
        // do something else
    }
}

在上面的 setter 中 willBeAnimated 应该是 YES 它是这样调用的:

- (void)someMethod {
    [UIView animateWithDuration:0.2 
                     animations:^{view.frame = someRect;}
                     completion:nil];
}

NO 在这种情况下:

- (void)someMethod {
    view.frame = someRect;
}

someMethod 这是 UIKit 内部的一个私有方法,我无法访问或更改,所以我必须以某种方式从“外部”确定它。

【问题讨论】:

  • 您能否将动画:(BOOL)作为参数添加到您的实现中,如果您想调用设置帧,无论它是否在动画块内被调用,都可以传递它?
  • @Mike 不幸的是,我没有调用 setFrame,我无权访问该代码。

标签: ios objective-c animation uiview uikit


【解决方案1】:

您应该能够在更改框架后立即检查您的UIView 子类的layeranimationKeys 以查看它是否正在动画。

- (void)setFrame:(CGRect)newFrame {
    [super setFrame:newFrame];
    BOOL willBeAnimated = [super.layer animationForKey:@"position"] ? YES : NO;
    if (willBeAnimated) {
        // do something 
    } else {
        // do something else
    }
}

您还可以使用animationsKeys 来检查是否有任何动画,在这种情况下只会返回position

此外,如果您想强制更改不被动画化,您可以使用performWithoutAnimation:

 [UIView performWithoutAnimation:^{
        [super setFrame:newFrame];
    }];

编辑

我通过测试发现的另一个花絮是,如果动画已经在进行中,您实际上可以停止动画,而是通过从图层中删除动画然后使用上述方法来立即进行更改。

- (void)setFrame:(CGRect)newFrame {
    [super setFrame:newFrame];
    BOOL willBeAnimated = [super.layer animationForKey:@"position"] ? YES : NO;
    BOOL shouldBeAnimated = // decide if you want to cancel the animation
    if (willBeAnimated && !shouldBeAnimated) {
        [super removeAnimationForKey:@"position"];
        [UIView performWithoutAnimation:^{
             [super setFrame:newFrame];
        }];
    } else {
        // do something else
    }
}

【讨论】:

    猜你喜欢
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-15
    • 2013-09-19
    • 1970-01-01
    相关资源
    最近更新 更多