我有一个视图,我想将其移动到ViewController
. 我想通过使用来做到这一点UIView.animateWithDuration
。在方法的完成块中,我想添加第二个视图。
ViewController
在我班级的代码下方。我已经在情节提要中设置了视图并通过 Outlet 连接了它
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func viewDidAppear(animated: Bool) {
animation()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBOutlet weak var card: UIView!
func animation() {
print("viewCenter \(self.view.center)")
print("cardCenter 1 \(self.card.center)")
UIView.animateWithDuration(1.0,
delay: 2.0,
options: UIViewAnimationOptions.CurveLinear,
animations: { () -> Void in
self.card.center = self.view.center
print("number of constraints on card: \(self.card.constraints.count)")
},
completion: { finished in
print("cardCenter 2 \(self.card.center)")
let rect = CGRect(x: 200, y: 300, width: 50, height: 50)
let tempView = UIView(frame: rect)
tempView.backgroundColor = UIColor.blueColor()
self.view.addSubview(tempView)
self.view.layoutIfNeeded()
print("cardCenter 3 \(self.card.center)")
})
}
}
动画工作正常,直到完成执行。第一个视图显示在动画之前的初始位置。然而,在控制台中,视图中心的打印坐标与主视图的中心相匹配
控制台输出
视图中心 (160.0, 284.0) 卡片中心 1 (140.0, 92.0) 卡片中心 2 (160.0, 284.0) 卡片中心 3 (160.0, 284.0)
在完成块中添加 UIView 时,谁能解释这种行为?
编辑
根据克里斯的评论,我添加了一些关于完成的登录card
约束
self.view.layoutIfNeeded()
。现在控制台输出确实显示了视图的初始坐标
新的控制台输出
viewCenter (160.0, 284.0)
cardCenter 1 (140.0, 92.0)
卡片上的约束数:0
cardCenter 2 (160.0, 284.0)
cardCenter 3 (140.0, 92.0)