如何在Swift中添加子视图时停止动画重置。

时间:2016-06-17 14:21:49

标签: ios swift animation addsubview

我试图让物品在云的位置产生。到目前为止,我对云的动画重复了我想要的方式,但是当我生成一个项目时,云动画从头开始重置。

添加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)

}

1 个答案:

答案 0 :(得分:2)

viewDidLayoutSubviews中的代码移至viewDidLoad。这应该可以解决您的问题。

每次添加新子视图时都会调用方法viewDidLayoutSubviews