【问题标题】:Adding a view in a completion block of UIView.animateWithDuration在 UIView.animateWithDuration 的完成块中添加视图
【发布时间】: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


【解决方案1】:

如果您在 Interface Builder 中有约束,请从 card 中删除约束并重试 - 您会发现它按预期工作。

在为带有约束的视图设置动画时,首先更新约束常量,然后在动画块中调用self.view.layoutIfNeeded()。正如您在示例中看到的那样,直接为属性设置动画会产生意想不到的结果。

【讨论】:

  • @Chris,视图没有限制。只需在界面生成器中放置一个视图并在控制器中拖动一个 IBOutlet。检查器不显示约束。将完成块设置为 nil 时,动画将起作用。我同意意外结果部分,但我找不到原因
  • 我还在看这个,真的很奇怪。我不记得以前见过这个,但是玩你的代码我得到了相同的结果。稍后会重新访问 - 同时,如果你也将中心设置在完成块中,你会没事的。虽然不理想,但它可以工作。
  • 感谢您对此进行调查。在此期间我会使用该工作,但它看起来很奇怪......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-07-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多