在 Swift 中添加子视图时如何阻止动画重置。?
Posted
技术标签:
【中文标题】在 Swift 中添加子视图时如何阻止动画重置。?【英文标题】:How to stop an animation from resetting when adding a subview in Swift.? 【发布时间】:2016-06-17 14:21:49 【问题描述】:我试图让物品在云的位置生成。到目前为止,我已经按照我想要的方式重复了云动画,但是当我生成一个项目时,云动画会从头开始重置。
添加subview
时,我有哪些选择?
Here is a gif from the project
override func viewDidLoad()
super.viewDidLoad()
override func didReceiveMemoryWarning()
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
override func viewDidLayoutSubviews()
super.viewDidLayoutSubviews()
gemCloudImage.center.x = 100
makeCloudFly()
override func viewDidAppear(animated: Bool)
super.viewDidAppear(true)
func makeCloudFly()
UIView.animateWithDuration(6, delay: 1, options: [.Autoreverse, .Repeat], animations:
self.gemCloudImage.center.x = self.view.frame.width - 100
, completion: nil)
@IBAction func buttonTapped(sender: AnyObject)
let positionX: CGFloat = gemCloudImage.layer.presentationLayer()!.frame.midX
let positionY: CGFloat = gemCloudImage.layer.presentationLayer()!.frame.midY
print(positionX)
print(positionY)
let chair = UIImageView()
chair.image = UIImage(named: "CHAIR1")
chair.frame = CGRectMake(positionX, positionY, 50, 50)
chair.frame = CGRect(x:positionX, y:positionY, width:50, height:50)
self.view.addSubview(chair)
【问题讨论】:
每当您添加子视图时,此行都会重新定位云。gemCloudImage.center.x = 100
【参考方案1】:
将viewDidLayoutSubviews
中的代码移动到viewDidLoad
。这应该可以解决您的问题。
每次添加新的子视图时都会调用方法viewDidLayoutSubviews
。
【讨论】:
我将云的初始X位置放入动画函数中,并将其移动到viewDidLoad中。它现在工作得很好!以上是关于在 Swift 中添加子视图时如何阻止动画重置。?的主要内容,如果未能解决你的问题,请参考以下文章