简体   繁体   中英

UILabel text fade out one by one

I want to figure out how to fade out text one by on in UILabel .

For example:

label.text = "abcdefg", I want to let the text fade out one by one -> 'a','b','c','d','e','f','g' fade out respectively.

How could I do this?

Thanks for all your answers, I want to clarify that I want an animation to fade out, something like UIViewAnimationOptions.CurveEaseInOut.

Thanks!

Use 2 labels and fade them in and out repeatedly, removing characters from each between each fade.

  1. first shown with abcdefg second hidden with abcdef
  2. fade first out and second in
  3. first hidden with abcde second shown with abcdef
  4. fade first in and second out
  5. etc

Or, use the view capture SDK to create images of your label with different text content and then animate through the images with some transition.

You can do it with using NSTimer and remove the last letter from string of its intervention. For example you can do something like this:

Simple class for fade text animation

class TextFadeAnimation {
    var text: String
    var timer: NSTimer?
    var block: ((text: String) -> Void)?

    init(text: String) {
        self.text = text
    }

    func startAnimation(resultTextBlock block: (text: String) -> Void) {
        self.block = block
        timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector("fadeOut"), userInfo: nil, repeats: true)
    }

    func stopAnimation() {
        if timer != nil {
            timer!.invalidate()
        }
    }

    @objc private func fadeOut() {
        if count(text) > 1 {
            text = text.substringToIndex(text.endIndex.predecessor())
            block!(text: text)
        } else {
            timer!.invalidate()
            block!(text: "")
        }
    }
}

Use example in ViewController

class ViewController: UIViewController {

    @IBOutlet weak var label: UILabel!
    var textFadeAnimation: TextFadeAnimation?

    override func viewDidLoad() {
        super.viewDidLoad()

        textFadeAnimation = TextFadeAnimation(text: "abcdefg")
        textFadeAnimation!.startAnimation(resultTextBlock: { (text: String) -> Void in
            self.label.text = text
        })
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM