在Swift中animation简单的淡入淡出?
我正在试图在Swift中制作一个简单的animation。 这是一个淡入。
我试过:
self.myFirstLabel.alpha = 0 self.myFirstButton.alpha = 0 self.mySecondButton.alpha = 0
那么,我有:
self.view.addSubview(myFirstLabel) self.view.addSubview(myFirstButton) self.view.addSubview(mySecondButton)
接着:
UIView.animateWithDuration(1.5, animations: { self.myFirstLabel.alpha = 1.0 self.myFirstButton.alpha = 1.0 self.mySecondButton.alpha = 1.0 })
我有我的viewDidLoad函数中的所有这一切。
我该如何做这项工作?
问题是你试图在视图控制器的生命周期中过早地开始animation。 在viewDidLoad中,视图刚刚创build,并且尚未添加到视图层次结构中,所以试图在此处animation一个子视图会产生不好的结果。
你应该做的是继续在viewDidLoad(或创build视图的位置)中设置视图的alpha值,然后等待viewDidAppear:方法被调用。 在这一点上,你可以开始你的animation没有任何问题。
override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) UIView.animateWithDuration(1.5, animations: { self.myFirstLabel.alpha = 1.0 self.myFirstButton.alpha = 1.0 self.mySecondButton.alpha = 1.0 }) }
0x7ffffff的答案是确定的,绝对是详尽的。
作为一个加号,我build议你以这种方式创build一个UIView扩展:
public extension UIView { /** Fade in a view with a duration - parameter duration: custom animation duration */ func fadeIn(duration duration: NSTimeInterval = 1.0) { UIView.animateWithDuration(duration, animations: { self.alpha = 1.0 }) } /** Fade out a view with a duration - parameter duration: custom animation duration */ func fadeOut(duration duration: NSTimeInterval = 1.0) { UIView.animateWithDuration(duration, animations: { self.alpha = 0.0 }) } }
斯威夫特-3
/// Fade in a view with a duration /// /// Parameter duration: custom animation duration func fadeIn(withDuration duration: TimeInterval = 1.0) { UIView.animate(withDuration: duration, animations: { self.alpha = 1.0 }) } /// Fade out a view with a duration /// /// - Parameter duration: custom animation duration func fadeOut(withDuration duration: TimeInterval = 1.0) { UIView.animate(withDuration: duration, animations: { self.alpha = 0.0 }) }
通过这种方式,无论您身在何处,您都可以:
let newImage = UIImage(named: "") newImage.alpha = 0 // or newImage.fadeOut(duration: 0.0) self.view.addSubview(newImage) ... newImage.fadeIn()
代码重用很重要!