【问题标题】:How do I animate opacity using swift?如何使用 swift 为不透明度设置动画?
【发布时间】:2014-11-18 13:19:04
【问题描述】:

有人可以为我提供一个在 swift 中为 Image View 的不透明度设置动画的示例吗??

我什至在目标 c 中找不到一个很好的例子

func showCorrectImage(element: AnyObject){

    var animation : CABasicAnimation = CABasicAnimation(keyPath: "opacity");

    animation.delegate = self

    animation.fromValue = NSValue(nonretainedObject: 0.0)
    animation.toValue = NSValue(nonretainedObject: 1.0)

    animation.duration = 1.0

    element.layer?.addAnimation(animation, forKey: nil)
}

我认为我拥有大部分权利(虽然不完全确定),有人可以帮助我吗?

元素 = 图像视图

先谢谢了!~

【问题讨论】:

    标签: swift uiimageview core-animation cabasicanimation nsvalue


    【解决方案1】:

    如果你需要一个简单的动画,为什么不直接使用 UIView 的animateWithDuration:animations: 方法呢?

    imageView.alpha = 0
    UIView.animateWithDuration(1.0) {
            imageView.alpha = 1
    }
    

    【讨论】:

    • @PugLvr28 看起来你是新来的。如果它解决了您的问题,您应该接受 Swipesight 的回答。
    【解决方案2】:

    你也可以这样写:

    animation.fromValue = 0.0
    animation.toValue = 1.0
    

    整个代码应该是这样的:

    let animation = CABasicAnimation(#keyPath(CALayer.opacity))
    animation.fromValue = 0.0
    animation.toValue = 1.0
    animation.duration = 1.0
    animation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
    element.layer?.addAnimation(animation, forKey: "fade")
    

    【讨论】:

      【解决方案3】:

      如果有人希望像 OP 最初尝试那样使用 CABasicAnimation,那么他原始代码的一个问题是他使用 NSValue 作为 toValue。我将它切换到 NSNumber 并且它对我有用。像这样

          fadeToVisible.fromValue = NSNumber(float: 0.0)
      

      【讨论】:

        【解决方案4】:

        你可以使用这个扩展方法(除非你想修改view's attributes本身):

        extension CALayer {
        
            func flash(duration: TimeInterval) -> Observable<Void> {
                let flash = CABasicAnimation(keyPath: "opacity")
        
                flash.fromValue = NSNumber(value: 0)
                flash.toValue = NSNumber(value: 1)
                flash.duration = duration
                flash.autoreverses = true
        
                removeAnimation(forKey: "flashAnimation")
                add(flash, forKey: "flashAnimation")
                opacity = 0     // Change the actual data value in the layer to the final value
            }
        }
        

        【讨论】:

          【解决方案5】:

          感谢@ylin0x81。对于 swift 5,我必须这样做:

          cell.imageView.alpha = 0.0;
          UIView.animate(withDuration: 1.0) {
              cell.imageView.alpha = 1
          }
          

          【讨论】:

            猜你喜欢
            • 2010-11-28
            • 1970-01-01
            • 2015-03-15
            • 2019-12-24
            • 2013-04-21
            • 2012-05-31
            • 2013-07-17
            • 1970-01-01
            • 2011-01-11
            相关资源
            最近更新 更多