使用数组中的字符串淡入/淡出标签

时间:2015-02-10 23:16:53

标签: ios swift ios8 xcode6 uilabel

func setOverlayTitle() {
    self.overlayLogo!.text = "Welcome"
    var hello: [String] = ["Bon Jour", "GUTEN\nMORGEN", "BONJOUR", "HOLA", "안녕하세요", "BUENOS DÍAS", "BUONGIORNO", "早安", "おはよう", "गुड मॉर्निंग"]

    for (var i = 1; i < hello.count-1; i++) {
    UIView.animateWithDuration(1.0, delay: 2.0, options: UIViewAnimationOptions.CurveEaseOut, animations: {
        self.overlayLogo!.alpha = 0.0
        }, completion: {
            (finished: Bool) -> Void in
            println(i)
            self.overlayLogo!.text = hello[i]

            // Fade in
            UIView.animateWithDuration(1.0, delay: 0.0, options: UIViewAnimationOptions.CurveEaseIn, animations: {
                self.overlayLogo!.alpha = 1.0
                }, completion: nil)
    })
  }

}

我有以下代码,我正在尝试迭代数组“hello”,同时以2秒的延迟淡入/淡出标签。但是这段代码不起作用! 目前它只打印9,9次,并且只打印/退出一次

1 个答案:

答案 0 :(得分:2)

问题是由您在那里使用的for循环引起的。您无法以这种方式获得所需的行为。在开始下一次迭代之前,for循环不会等待标签动画完成。在每个动画周期完成后,您可以从方法本身进行递归调用。

您需要在类中声明一个变量并实现如下方法:

var iterator = 1;

override func viewDidLoad()
{

    super.viewDidLoad()
    self.lblAnime!.text = "Welcome"
    setOverlayTitle()
}

func setOverlayTitle()
{

    var hello: [String] = ["Bon Jour", "GUTEN\nMORGEN", "BONJOUR", "HOLA", "안녕하세요", "BUENOS DÍAS", "BUONGIORNO", "早安", "おはよう", "गुड मॉर्निंग"]

    UIView.animateWithDuration(1.0, delay: 2.0, options: UIViewAnimationOptions.CurveEaseOut, animations:
       {
            self.lblAnime!.alpha = 0.0
       },
       completion:
       {(finished: Bool) -> Void in
            println(self.iterator)
            self.lblAnime!.text = hello[self.iterator]

            // Fade in
            UIView.animateWithDuration(1.0, delay: 0.0, options: UIViewAnimationOptions.CurveEaseIn, animations:
                {
                     self.lblAnime!.alpha = 1.0
                },
                completion:
                {(finished: Bool) -> Void in
                     self.iterator++

                     if self.iterator < hello.count
                     {
                         self.setOverlayTitle();
                     }
                })
       })
}