【发布时间】:2015-09-29 20:15:53
【问题描述】:
我有一个要移动到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 时的这种行为?
编辑
根据 Chris 的评论,我添加了一些登录约束 card 和self.view.layoutIfNeeded() 完成。现在控制台输出确实显示了视图的初始坐标
新控制台输出
viewCenter (160.0, 284.0)
卡片中心 1 (140.0, 92.0)
卡上的约束数量:0
卡片中心 2 (160.0, 284.0)
卡片中心 3 (140.0, 92.0)
【问题讨论】:
-
你有什么限制吗?
-
即使您没有约束,您也可能需要在您的 xib 中明确禁用自动布局。
-
我正在使用需要自动布局的尺寸类。关键是我不明白为什么在没有完成块中的代码的情况下动画效果很好。但是当添加一个与第一个视图没有关系或约束的额外视图时,我得到了这些意外行为
标签: ios swift uiview uiviewanimation completion