How to display an container view with animation in iOS?

Blaszard picture Blaszard · Oct 3, 2014 · Viewed 11.3k times · Source

I want to display my own custom view when an user taps an button in the original view controller, and so I tried to define the following function which is caused when the user taps the button:

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)
}

When the user taps the button however, the container view is displayed on the screen abruptly, but I want to make it shown more smoothly. So next I tried to rewrite it with animation, but I've hit the wall, since I don't know what I should write in order to display it with animation:

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)
})

This returns an error: '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:]'.

I think I should use the method, but I don't know what code to write in animations: block and what to completion: block.

How can I write the animation code?

Answer

Greg picture Greg · Oct 3, 2014

You can use view transitioning like so:

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

This will animate the change in the contents of the container view (to reflect the subview being added), instead of trying to animate the view controller transition itself. You will not need to use transitionFromViewController at all this way.