在一个UIView中为每个元素设置动画

时间:2017-03-11 10:59:42

标签: ios swift animation

我想为UIButton中的每个UILabel / UIView制作动画。例如,每个UIButton一个接一个地消失,只有一行代码。这可能吗?我在Github搜索,但找不到任何东西。我发现每个UILabelUIButton逐个动画制作很多工作。谢谢。

3 个答案:

答案 0 :(得分:2)

let duration = 0.5

view.subviews.flatMap { $0 as? UILabel ?? $0 as? UIButton }.enumerated().forEach { i, o in UIView.animate(withDuration: duration, delay: Double(i) * duration, animations: { o.alpha = 0 }) }

在“一行”中。

在我的手机上输入此内容,如果我犯了一些错误请随时纠正:)

答案 1 :(得分:1)

您可以通过迭代UIView的子视图并检查它是UILabel还是UIButton来自行完成!做类似的事情:

var counter : Double = 0

func hideSubviews(view:UIView){

    for tempView in view.subviews{

        let when = DispatchTime.now() + counter

        if tempView is UIButton || tempView is UILabel{

            DispatchQueue.main.asyncAfter(deadline: when) {

                UIView.animate(withDuration: 1, animations: {
                    //this does fade out, change 0 to 1 for fade in
                    tempView.alpha = 0.0
                })
            }
        }
        //increment by gap you want
        counter += 1
    }
}

修改

叹息我忘了这个更简单的方法,你可以在animate函数中使用delay属性:

var counter = 0

func hideSubviews(view:UIView){

    for tempView in view.subviews{

        if tempView is UIButton || tempView is UILabel{

            UIView.animate(withDuration: 0.3, delay: TimeInterval(counter), options: .init(rawValue: 0), animations: {

                tempView.alpha = 0.0

            }, completion: nil)
        }

        counter += 1
    }
}

然后在viewDidAppear或任何地方,只需调用该函数并传入视图:

override func viewDidAppear(_ animated: Bool) {

     super.viewDidAppear(animated)

     hideSubviews(view: view)
}

答案 2 :(得分:1)

您可以创建并调用一个函数作为您要查找的单行代码,您可以在其中添加一个您希望淡入的按钮或标签数组。我将举例说明您可以复制粘贴,它应该可以工作。您唯一需要做的就是在Storyboard中连接UIButton出口。

    import UIKit

class ViewController: UIViewController {

@IBOutlet weak var button1: UIButton!

@IBOutlet weak var button2: UIButton!

@IBOutlet weak var button3: UIButton!

var count = 0

override func viewDidLoad() {
    super.viewDidLoad()

}

override func viewDidAppear(_ animated: Bool) {

    let allButtons = [button1, button2, button3]

    fadeInButtons(buttons: allButtons as! [UIButton])

}

func fadeInButtons(buttons: [UIButton]) {

    UIView.animate(withDuration: 0.4, animations: {

            buttons[self.count].alpha = 0


    }) { (value) in

        if self.count < buttons.count - 1 {

            self.count += 1

            self.fadeInButtons(buttons: buttons)

        }

       }





}

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


}

带有按钮的故事板应该如下所示

Storyboard

所以你需要做的就是调用fadeInButtons函数(按钮:[UIButton])并传递一个你要淡入的按钮数组,它将在下一个之后执行。你可以修改它以包括标签func fadeInButtons(按钮:[UIButton],标签:[UILabel])。您可以修改每个动画的时间,在此示例中,每个淡入淡出的动画都需要0.4才能完成。