如果目标是捕捉
opacity
当应用程序进入后台时,你可以为其添加一个观察者
UIApplicationDidEnterBackground
,捕捉不透明度,取消动画,并设置
alpha
. E、 g.在Swift中:
class ViewController: UIViewController {
@IBOutlet weak var viewToAnimate: UIView!
private var observer: NSObjectProtocol!
override func viewDidLoad() {
super.viewDidLoad()
observer = NotificationCenter.default.addObserver(forName: .UIApplicationDidEnterBackground, object: nil, queue: .main) { [weak self] notification in
if let opacity = self?.viewToAnimate.layer.presentation()?.opacity {
self?.viewToAnimate.layer.removeAllAnimations()
self?.viewToAnimate.alpha = CGFloat(opacity)
}
}
}
deinit {
NotificationCenter.default.removeObserver(observer)
}
// I'm just doing a basic animation, but the idea is the same whatever animation you're doing
@IBAction func didTapButton(_ sender: Any) {
UIView.animate(withDuration: 10) {
self.viewToAnimate.alpha = 0
}
}
}
如果你的目标是即使应用程序被终止也要记住它,那么你需要将其保存在持久存储中。但是如果你的目标只是设定
当应用程序挂起和/或在后台运行时,上述内容就足够了。