[英]Adding a view in a completion block of UIView.animateWithDuration
我有一個視圖,我想將其移動到ViewController
的主視圖的中心。 我想通過使用UIView.animateWithDuration
來做到這UIView.animateWithDuration
。 在方法的完成塊中,我想添加第二個視圖。
在我的ViewController
類的代碼下方。 我已經在故事板中設置了視圖並通過插座連接它
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)")
})
}
}
動畫工作正常,直到執行完成。 第一個視圖顯示在動畫之前的初始位置。 然而,在控制台中,視圖中心的打印坐標與主視圖的中心相匹配
viewCenter (160.0, 284.0) cardCenter 1 (140.0, 92.0) cardCenter 2 (160.0, 284.0) cardCenter 3 (160.0, 284.0)
在完成塊中添加 UIView 時,任何人都可以解釋這種行為嗎?
根據 Chris 的評論,我添加了一些關於card
和
self.view.layoutIfNeeded()
到完成。 現在控制台輸出確實顯示了視圖的初始坐標
視圖中心 (160.0, 284.0)
卡中心 1 (140.0, 92.0)
卡上的約束數:0
卡中心 2 (160.0, 284.0)
卡中心 3 (140.0, 92.0)
如果您在 Interface Builder 中有約束,請從card
刪除約束card
試 - 您會發現它按預期工作。
當動畫帶有約束的視圖時,首先更新約束常量,然后在動畫塊中調用self.view.layoutIfNeeded()
。 正如您在示例中所見,直接對屬性進行動畫處理會產生意想不到的結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.