我有一个 View ,我想移动到 ViewController
主视图的中心。我想通过使用 UIView.animateWithDuration
来做到这一点。在方法的完成 block 中,我想添加第二个 View 。
在我的 ViewController
类的代码下方。我已经在 Storyboard 中设置了 View 并通过 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)")
})
}
动画工作正常,直到执行完成的那一刻。第一个 View 显示在动画之前的初始位置。然而,在控制台中, View 中心的打印坐标与主视图的中心相匹配
控制台输出
viewCenter (160.0, 284.0) cardCenter 1 (140.0, 92.0) cardCenter 2 (160.0, 284.0) cardCenter 3 (160.0, 284.0)
谁能解释在完成 block 中添加 UIView 时的这种行为?
编辑
根据 Chris 的评论,我添加了一些关于 card
和
的日志记录限制
self.view.layoutIfNeeded()
完成。现在控制台输出确实显示了 View 的初始坐标
新控制台输出
viewCenter (160.0, 284.0)
卡片中心 1 (140.0, 92.0)
卡上的约束数:0
卡片中心 2 (160.0, 284.0)
卡片中心 3 (140.0, 92.0)
最佳答案
如果您在 Interface Builder 中有约束,请从 card
中删除约束并重试 - 您会发现它按预期工作。
当为带有约束的 View 设置动画时,首先更新约束常量,然后在动画 block 内调用 self.view.layoutIfNeeded()
。正如您在示例中看到的那样,直接对属性进行动画处理会产生意想不到的结果。
关于ios - 在 UIView.animateWithDuration 的完成 block 中添加 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32852992/