当用户点击原始视图控制器中的按钮时,我想显示自己的自定义视图,因此我尝试定义当用户点击按钮时导致的以下功能:
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:
阻止什么代码。
如何编写动画代码?
答案 0 :(得分:15)
你可以这样使用view transitioning:
UIView.transitionWithView(self.view, duration: 0.5, options: .TransitionFlipFromLeft, animations: { _ in
self.view.addSubview(self.vc.view)
}, completion: nil)
这将动画容器视图内容的更改(以反映正在添加的子视图),而不是尝试为视图控制器转换本身设置动画。您不需要以这种方式使用transitionFromViewController
。
答案 1 :(得分:2)
swift 4版@Greg的回答
UIView.transition(with: self.view, duration: 0.5, options: .transitionFlipFromLeft, animations: {
self.view.addSubview(self.vc.view)
}, completion: nil)