How to display container view with animation in iOS?

I want to show my own custom view when the user enters a button in the original view controller, so I tried to define the following function that occurs when the user clicks 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)
}

      

If the user clicks the button, the container will appear on the screen suddenly, but I want to make it smoother. So I tried to rewrite it with animation, but I hit the wall as I don't know what I should write 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)
})

      

It 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 this method, but I don't know what code to write in the block animations:

and what to do with completion:

.

How do I write animation code?

+3


source to share


2 answers


You can use the transition view like this:

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

      



This will change the contents of the container's content (to reflect the addition of the subview) instead of trying to animate the transition of the view controller itself. You won't need to use transitionFromViewController

that way.

+12


source


swift 4 version of @Greg's answer



UIView.transition(with: self.view, duration: 0.5, options: .transitionFlipFromLeft, animations: {
                self.view.addSubview(self.vc.view)
            }, completion: nil)

      

0


source







All Articles