ios - 在 UIView.animateWithDuration 的完成 block 中添加 View

标签 ios swift uiview uiviewanimation completion

我有一个 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/

相关文章:

swift - 使用 Swift URLSession 将 header 传递给 URL

ios - 区分在自定义UIView中点击了哪个按钮

iOS - 在标签栏中初始化 View Controller

iOS 团队配置。 Xcode 不提供我们的团队配置文件作为选项。为什么?

ios - 与 UIActivityViewController 共享 UiWebView 内容

swift - UIView 中神秘的 UIColor 行为以及 Swift 中的一般情况

iphone - UIView 隐藏属性...还有更多吗?

ios - 分配初始化保留?

c# - Xamarin Forms 应用入门

swift - 通过远程通知从 AppDelegate 推送到 UINavigationController