如何在更改UIView的隐藏模式时添加动画?

51

我想在更改视图的隐藏模式时添加动画效果,即

my_view.hidden=YES;

我在导航栏中添加了一个按钮。当我们点击它时,新视图将被设置为非隐藏状态。它绘制在导航表的上方。


你想要什么样的动画效果,例如淡入淡出、翻转等? - Erik B
苹果声称多年来.isHidden是可动画化的,但这完全是荒谬的,因为它实际上并不能。 - Fattie
12个回答

0
如果您希望使用更复杂的动画类型或UIView不支持的动画,则可以考虑使用另一个版本。
- (void)setHidden:(BOOL)hidden withAnimationDuration:(NSTimeInterval)duration
{
    CATransition* transition = ({
        CATransition* its = [CATransition animation];
        its.duration = duration;
        its.timingFunction =
            [CAMediaTimingFunction
             functionWithName: kCAMediaTimingFunctionEaseInEaseOut];
        its.type = kCATransitionPush;
        its.subtype = (hidden ? @"fromBottom" : @"fromTop");
        its
    });

    UIView* containerView = self.superview;
    [containerView.layer removeAllAnimations];
    [containerView.layer addAnimation: transition forKey: kCATransition];

    self.hidden = hidden;

    if (!hidden) {
        [self.superview bringSubviewToFront: self];
    }
}

0
这是我用来模拟视图“增长”和“缩小”的代码,通过点击“显示更多…”和“显示更少…”按钮。这个方法让我可以在storyboard中创建两个视图,以便约束在不同的iOS设备上按预期工作,而我不需要自定义编写所有的约束。这个方法是基于Palyancodr的答案建立的。
@IBAction func showMoreOrLessAction(_ sender: Any) {
    // if small view showing
    if showMoreLargeView.isHidden {
        showMoreSmallView.isHidden = true

        //showMoreLargeView.isHidden = false
        UIView.animate(withDuration: 0.2, delay: 0, options: [], animations: {
            self.showMoreLargeView.alpha = 1 // Here you will get the animation you want
        }, completion: { _ in
            self.showMoreLargeView.isHidden = false // Here you hide it when animation done
        })
    }
    else { // large view showing
        //showMoreSmallView.isHidden = false
        UIView.animate(withDuration: 0.2, delay: 0, options: [], animations: {
            self.showMoreSmallView.alpha = 1 // Here you will get the animation you want
        }, completion: { _ in
            self.showMoreSmallView.isHidden = false // Here you hide it when animation done
        })

        showMoreLargeView.isHidden = true
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接