Swift中的顺序淡入

时间:2019-06-12 10:14:20

标签: ios swift fadein

我使用了出色的答案here来实现文本标签的淡入。

但是,我想引入一个延迟,以便可以依次淡入多个文本标签。

到目前为止(取自答案),我正在使用:

extension UIView {

    func fadeIn(duration: TimeInterval = 1.0, delay: TimeInterval = 0.0, completion: @escaping ((Bool) -> Void) = {(finished: Bool) -> Void in}) {
        UIView.animate(withDuration: duration, delay: delay, options: UIViewAnimationOptions.curveEaseIn, animations: {
            self.alpha = 1.0
        }, completion: completion)  }
}

然后使用:

实施
override func viewDidLoad() {

        self.line1Outlet.alpha = 0
        self.line1Outlet.fadeIn(completion: {
            (finished: Bool) -> Void in
        })

    }

我当时认为最好的解决方案是将延迟作为扩展中的参数来实现,这样我就可以轻松地为每个标签添加不同的延迟。 (例如

override func viewDidLoad() {

        self.line1Outlet.alpha = 0
        //add a parameter here for the delay (here line 1 gets '1second' then line 2 could come in after 2seconds etc)
        self.line1Outlet.delay = 1second
        self.line1Outlet.fadeIn(completion: {
            (finished: Bool) -> Void in
        })

    }

我尝试将self.delay添加到扩展名(在self.alpha之下),但这不起作用,而且我不确定如何重构该扩展名以允许我使用它。

然后,对此的答案将是实现顺序渐变的可重用方法,希望该方法对许多其他人有用!

1 个答案:

答案 0 :(得分:1)

在您创建的extension中,首先在self.alpha = 0.0函数的顶部添加fadeIn,即

extension UIView {
    func fadeIn(duration: TimeInterval = 1.0, delay: TimeInterval = 0.0, completion: ((Bool)->())? = nil) {
        self.alpha = 0.0
        UIView.animate(withDuration: duration, delay: delay, options: .curveEaseIn, animations: {
            self.alpha = 1.0
        }, completion: completion)
    }
}

现在假设您在labels中有3个view,即

@IBOutlet weak var label1: UILabel!
@IBOutlet weak var label2: UILabel!
@IBOutlet weak var label3: UILabel!

依次将animation添加到labels

self.label1.fadeIn(delay: 0.1) { _ in
    self.label2.fadeIn(delay: 0.2, completion: { _ in
        self.label3.fadeIn(delay: 0.3, completion: { _ in
            print("Done All")
        })
    })
}

由于duration parameter方法中的fadeIn具有default value,因此我们可以避免这种情况。

调用fadeIn的方式是一种调用方式。由于该方法包含多个default params,因此也可以通过其他方式调用它。

详细了解 default parameters here

enter image description here

编辑:

要最初隐藏labels,请在alpha本身中将所有labels的{​​{1}}设置为0

enter image description here