13

当用户点击原始视图控制器中的按钮时,我想显示我自己的自定义视图,因此我尝试定义用户点击按钮时导致的以下函数:

func show() {
    vc = UIViewController()
    var button = UIButton(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
    button.backgroundColor = UIColor.redColor()
    button.addTarget(self, action: "hide", forControlEvents: UIControlEvents.TouchDown)
    vc.view.addSubview(button)

    self.addChildViewController(vc)
    self.view.addSubview(vc.view)
    vc.didMoveToParentViewController(self)
}

然而,当用户点击按钮时,容器视图会突然显示在屏幕上,但我想让它显示得更流畅。所以接下来我尝试用动画重写它,但是我碰壁了,因为我不知道我应该写什么才能用动画显示它:

transitionFromViewController(self, toViewController: vc, duration: 0.5, options: UIViewAnimationOptions.TransitionCrossDissolve, animations: {() -> Void in
        self.addChildViewController(self.vc)
        self.view.addSubview(self.vc.view)
        }, completion: {
        Bool -> Void in
        self.vc.didMoveToParentViewController(self)
})

这将返回一个错误:'NSInvalidArgumentException', reason: 'Children view controllers <mmmmlvalsllsl.ViewController: 0x7fc980f71f70> and <UIViewController: 0x7fc980f6dd00> must have a common parent view controller when calling -[UIViewController transitionFromViewController:toViewController:duration:options:animations:completion:]'

我想我应该使用该方法,但是我不知道要在animations:块中编写什么代码以及要completion:阻止什么。

如何编写动画代码?

4

2 回答 2

29

您可以像这样使用视图转换

UIView.transitionWithView(self.view, duration: 0.5, options: .TransitionFlipFromLeft, animations: { _ in
    self.view.addSubview(self.vc.view)
}, completion: nil)

这将为容器视图的内容更改设置动画(以反映正在添加的子视图),而不是尝试为视图控制器转换本身设置动画。您根本不需要使用transitionFromViewController这种方式。

于 2014-10-02T23:43:00.020 回答
5

swift 4 版本的@Greg's answer

UIView.transition(with: self.view, duration: 0.5, options: .transitionFlipFromLeft, animations: {
                self.view.addSubview(self.vc.view)
            }, completion: nil)
于 2018-03-09T10:35:03.767 回答