Make a simple fade in animation in Swift?

前端 未结 6 1020
一个人的身影
一个人的身影 2021-01-30 08:08

I am trying to make a simple animation in Swift. It is a fade in.

I attempted:

self.myFirstLabel.alpha = 0
self.myFirstButton.alpha = 0
         


        
6条回答
  •  不思量自难忘°
    2021-01-30 08:53

    0x7ffffff's answer is ok and definitely exhaustive.

    As a plus, I suggest you to make an UIView extension, in this way:

    public extension UIView {
    
      /**
      Fade in a view with a duration
    
      - parameter duration: custom animation duration
      */
      func fadeIn(duration duration: NSTimeInterval = 1.0) {
        UIView.animateWithDuration(duration, animations: {
            self.alpha = 1.0
        })
      }
    
      /**
      Fade out a view with a duration
    
      - parameter duration: custom animation duration
      */
      func fadeOut(duration duration: NSTimeInterval = 1.0) {
        UIView.animateWithDuration(duration, animations: {
            self.alpha = 0.0
        })
      }
    
    }
    

    Swift-3

    /// Fade in a view with a duration
    /// 
    /// Parameter duration: custom animation duration
    func fadeIn(withDuration duration: TimeInterval = 1.0) {
        UIView.animate(withDuration: duration, animations: {
            self.alpha = 1.0
        })
    }
    
    /// Fade out a view with a duration
    ///
    /// - Parameter duration: custom animation duration
    func fadeOut(withDuration duration: TimeInterval = 1.0) {
        UIView.animate(withDuration: duration, animations: {
            self.alpha = 0.0
        })
    }
    

    In this way you can do this wherever in your code:

    let newImage = UIImage(named: "")
    newImage.alpha = 0 // or newImage.fadeOut(duration: 0.0)
    self.view.addSubview(newImage)
    ... 
    newImage.fadeIn()
    

    Code reuse is important!

提交回复
热议问题