Harry Collins Harry Collins - 3 months ago 16
Swift Question

Fading In And Fading Out A Label Infinitively With separate `text`

I have a label in xCode that I want to infinitely fade between a word and then the current time.

I've had a look online and can find a single fade but am new to Swift so I'm struggling to adapt this to my need.

Any help would be amazing, Thanks!

Answer

Here is an example of how to do this:

@IBOutlet weak var label: UILabel!

@IBAction func fade_out(sender: AnyObject) {
    fade(label)
}

@IBAction func reset(sender: AnyObject) {
    label.text = "label"
}

func fade(label : UILabel) {
     UIView.animateWithDuration(1.0, delay: 0.0, options: UIViewAnimationOptions.CurveEaseOut, animations: {
         label.alpha = 0.0
     }, completion: nil)

     UIView.animateWithDuration(2.0, delay: 0.0, options: UIViewAnimationOptions.CurveEaseIn, animations: {
         label.alpha = 1.0
         label.text = String(NSDate())
     }, completion: nil)
}

What I do is that I fade out the label first with UIViewAnimationOptions.CurveEaseOut and then fade it in again with todays date with UIViewAnimationOptions.CurveEaseIn.

Here is a test project I created for you so that you can see how I have done it.

Edit
To do it infinity, you can do it like this and without a button

var timer = NSTimer()
var b = false

override func viewDidLoad() {
    super.viewDidLoad()
    self.timer = NSTimer.scheduledTimerWithTimeInterval(2, target: self, selector: #selector(ViewController.fade), userInfo: nil, repeats: true)
}

func fade() {
        if b{
            UIView.animateWithDuration(1.0, delay: 0.0, options: UIViewAnimationOptions.CurveEaseOut, animations: {
                self.label.alpha = 0.0
                self.label.text = "Label"
                }, completion: nil)

            UIView.animateWithDuration(1.0, delay: 0.0, options: UIViewAnimationOptions.CurveEaseIn, animations: {
                self.label.alpha = 1.0
                self.label.text = String(NSDate())
                }, completion: nil)

            b = false
        }
        else{
            UIView.animateWithDuration(1.0, delay: 0.0, options: UIViewAnimationOptions.CurveEaseOut, animations: {
                self.label.alpha = 0.0
                self.label.text = String(NSDate())
                }, completion: nil)

            UIView.animateWithDuration(1.0, delay: 0.0, options: UIViewAnimationOptions.CurveEaseIn, animations: {
                self.label.alpha = 1.0
                self.label.text = "Label"
                }, completion: nil)

            b = true
        }

    }
Comments