extension UIView {
func startBlinking() {
UIView.animate(withDuration: 0.8, delay: 0.0, options: [.allowUserInteraction, .curveEaseInOut, .autoreverse, .repeat], animations: { self.alpha = 0 }, completion: nil)
}
}
我如何使用它?
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
monthLabel.startBlinking()
}
第一次调用method时,它闪烁...但是第二次出现视图时,标签消失,而仅此而已。
为什么它不再起作用?
我的日志:
did load did appear start blinking did appear start blinking
答案 0 :(得分:1)
尝试:
import UIKit
protocol Then {}
extension Then {
func then(_ block: (Self) -> Void) -> Self {
block(self)
return self
}
}
extension UIView: Then {}
class ViewController: UIViewController {
private var animate: ((Bool) -> Void)?
private var canAnimate: Bool = true
override func viewDidLoad() {
super.viewDidLoad()
let label = UILabel().then {
$0.text = "Hello World!"
$0.textColor = .black
$0.translatesAutoresizingMaskIntoConstraints = false
}
view.addSubview(label)
NSLayoutConstraint.activate([
label.centerXAnchor.constraint(equalTo: view.centerXAnchor),
label.centerYAnchor.constraint(equalTo: view.centerYAnchor)
])
animate = { [weak self] (forward) in
UIViewPropertyAnimator.runningPropertyAnimator(withDuration: 1.0, delay: 0.0, options: [.curveLinear, .autoreverse, .repeat], animations: {
label.alpha = forward ? 0.0 : 1.0
}, completion: { [weak self] _ in
if self?.canAnimate ?? true {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.25, execute: {
self?.animate?(!forward)
})
}
}).startAnimation()
}
animate?(true)
DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
let controller = UIViewController()
self.navigationController?.pushViewController(controller, animated: true)
}
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
canAnimate = false
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
canAnimate = true
animate?(true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
答案 1 :(得分:0)
您需要重新启动alpha
func startBlinking() {
self.layer.removeAllAnimations()
self.alpha = 1.0
UIView.animate(withDuration: 0.8, delay: 0.0, options: [.allowUserInteraction, .curveEaseInOut], animations: { self.alpha = 0.0 }, completion: nil)
}