我有一段代码可以为 mainView 提供 Spring 效果。
但我没有得到想要的效果,我只能通过 Storyboards 将 Transition 样式应用到 ViewController。
override func viewDidLoad()
{
super.viewDidLoad()
self.statusBarHidden = UIApplication.shared.isStatusBarHidden
UIApplication.shared.setStatusBarHidden(true, with: .none)
self.mainView = UIView(frame: CGRect(x: self.view.getWidth/20, y:self.view.getHeight/6, width:self.view.getWidth/1.3 , height: self.view.getHeight/1.3))
self.mainView.backgroundColor = UIColor.blue
self.mainView.center.x = self.view.center.x
self.mainView.center.y = self.view.center.y
self.mainView.transform = CGAffineTransform(scaleX: 0.8, y: 1.2) // initial view distorted scale so it has a starting point for the animation
self.view.addSubview(self.mainView)
UIView.animate(withDuration: 0.3, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0, options: [], animations: {
self.mainView.transform = .identity // get back to original scale in an animated way
}, completion: nil)
}
你能帮忙把 Spring 效果带到mainView吗?
谢谢
最佳答案
要使用动画,您应该了解 View Controller 生命周期。这对于您描述的情况至关重要,因为您应该了解何时以及为何开始动画。
首先请阅读官方关于生活圈documentation .
代码,但试着理解为什么它现在可以工作:
class ViewController: UIViewController {
var mainView = UIView()
override func viewDidLoad() {
super.viewDidLoad()
addMainView()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
animateMainView()
}
func addMainView() {
self.mainView = UIView(frame: CGRect(x: self.view.frame.width/20, y:self.view.frame.height/6, width:self.view.frame.width/1.3 , height: self.view.frame.height/1.3))
self.mainView.backgroundColor = UIColor.blue
self.mainView.center.x = self.view.center.x
self.mainView.center.y = self.view.center.y
self.view.addSubview(self.mainView)
}
func animateMainView() {
self.mainView.transform = CGAffineTransform(scaleX: 0.8, y: 1.2) // initial view distorted scale so it has a starting point for the animation
UIView.animate(withDuration: 0.9, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0, options: [], animations: {
self.mainView.transform = .identity // get back to original scale in an animated way
}, completion: nil)
}
}
动画示例:
关于ios - 查看动画不起作用 - ios Swift 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43407863/