动画结束后从超级视图中删除UIView

时间:2011-09-13 21:20:24

标签: ios

我正在动画UIView(alpha)属性,我想在动画完成后我可以从超级视图中删除它。

    -(void) hideOverlayView
{
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:1.0];

    [topView setAlpha:0];

    [UIView commitAnimations];

}

一个选项是使用带延迟选项的performSelector但是有更紧凑的方法吗?

更新1:

为什么此代码会立即删除视图?

[UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:1.0];
    [UIView setAnimationDelegate:topView];
    [UIView setAnimationDidStopSelector:@selector(removeFromSuperview)];

    [topView setAlpha:0];

    [UIView commitAnimations];

我应该提一下,我首先做的是淡入淡出动画然后淡出。上面是淡出代码,可以立即删除UIView而不是淡出效果。

5 个答案:

答案 0 :(得分:24)

直接从UIView docs

[UIView animateWithDuration:0.2
     animations:^{view.alpha = 0.0;}
     completion:^(BOOL finished){ [view removeFromSuperview]; }];

或者在您的具体案例中:

[UIView animateWithDuration:1.0
    animations:^{topView.alpha:0.0;}
    completion:^(BOOL finished){ [topView removeFromSuperview]; }];

答案 1 :(得分:4)

您可以使用块来执行此类操作;)
像这样:

[UIView animateWithDuration:1.0 animations:^{
    topView.alpha = 1.0; topView.alpha = 0.0;
} completion:^(BOOL success) {
    if (success) {
        [topView removeFromSuperview];
    }
}];

答案 2 :(得分:2)

如果您正在使用CAKeyframeAnimation或类似的,则需要为动画分配委托。

我创建了这个类作为委托(Swift 3):

class AnimationDelegate: NSObject, CAAnimationDelegate {
    typealias AnimationCallback = (() -> Void)

    let didStart: AnimationCallback?
    let didStop: AnimationCallback?

    init(didStart: AnimationCallback?, didStop: AnimationCallback?) {
        self.didStart = didStart
        self.didStop = didStop
    }

    internal func animationDidStart(_ anim: CAAnimation) {
        didStart?()
    }

    internal func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
        didStop?()
    }
}

然后我可以像这样使用那个类:

let animateView = UIView()
let anim = CAKeyframeAnimation(keyPath: "position")
anim.delegate = AnimationDelegate(
            didStart: nil,
            didStop: {
                heart.removeFromSuperview()
        })
animateView.layer.add(anim, forKey: "animate position along path")

答案 3 :(得分:1)

如果你有一个类变量的视图,并且可以重新创建以淡出它,然后再显示新的数据,你可能需要这样的东西:

Swift 4

func removeView(animated: Bool) {
    guard let index = subviews.index(of: viewToRemove) else { return }
    animated ? removeSubViewWithFading(from: index) :
        viewToRemove.removeFromSuperview()
}

private func removeSubViewWithFading(from index: Int) {
    let view = self.subviews[index]
    UIView.animate(withDuration: 1, animations: {
        view.alpha = 0
    }, completion: { _ in
        if self.subviews.count > index {
            view.removeFromSuperview()
        }
    })
}

答案 4 :(得分:0)

如果你定位> iOS 4,那么你应该看看块。否则,请setAnimationDelegate:

专门查看UIView的文档