我使用优秀的答案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下面),但这不起作用,我不确定如何重构该扩展以允许我所追求的东西。
解决这个问题的方法是一种实现顺序渐变的可重用方法,希望对其他人有用!
最佳答案
在您创建的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的更多信息。编辑:
对于最初隐藏的
labels
,在alpha
本身中将所有labels
的0
设置为storyboard
。