-1

I'm trying to make an animated UILabel using CATransition which can fade out the original text and fade in the new text when I touch the screen. Here is my code and I can't figure out why there is no animation. Please help me. I'm using Xcode 7.3.

var subtitle:UILabel!
var winsize:CGSize!

override func viewDidLoad() {
    super.viewDidLoad()

    let animation = CATransition()
    animation.type = kCATransitionFade
    animation.duration = 0.75
    animation.fillMode = kCAFillModeBoth
    animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
    animation.delegate = self

    self.subtitle = UILabel()
    self.subtitle.text = "f"
    self.subtitle.frame = CGRectMake(45, 30, 200, 50)
    self.subtitle.font = UIFont.systemFontOfSize(25)
    self.subtitle.textColor = UIColor.grayColor()
    self.view.addSubview(self.subtitle)
    self.subtitle.layer.addAnimation(animation, forKey: "animation")
}

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {

    self.subtitle.text="HighSchool"
}

With help from @matt, the following code works.

var subtitle:UILabel!
var winsize:CGSize!

override func viewDidLoad() {
    super.viewDidLoad()

    winsize = self.view.frame.size

    self.subtitle = UILabel()
    self.subtitle.text = "f"
    self.subtitle.frame = CGRectMake(45, 30, 200, 50)
    self.subtitle.font = UIFont.systemFontOfSize(25)
    self.subtitle.textColor = UIColor.grayColor()
    self.view.addSubview(self.subtitle)

    UIView.transitionWithView(self.subtitle, duration: 0.5, options: UIViewAnimationOptions.TransitionCrossDissolve, animations: nil, completion: nil)
}


override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    self.subtitle.text="HighSchool"
}
  • First thank for your help. What I want to do is to make a UILabel that when I change its text, the original text fade out and new text fade in, like the one shown in http://stackoverflow.com/questions/3073520/animate-text-change-in-uilabel – user2232335 Apr 16 '16 at 20:19
  • Well, your code doesn't do anything like that. You are just saying `self.subtitle.text="HighSchool"`. There's no fade animation there. It's not going to fall out of the sky; you have to write in the animation explicitly. Call `transitionWithView:duration:options:animations:completion:` and change the text. It's three lines of code, super simple. – matt Apr 16 '16 at 20:22
  • It works!!! Thank you so much! – user2232335 Apr 16 '16 at 20:39

1 Answers1

0

Like this:

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    let opts : UIViewAnimationOptions = .TransitionCrossDissolve
    UIView.transitionWithView(self.subtitle, duration: 0.75, options: opts, animations: {
        self.subtitle.text="HighSchool"
    }, completion: nil)
}
matt
  • 447,615
  • 74
  • 748
  • 977