Josh
Josh

Reputation: 307

How do I present a view controller inside another in Swift?

I am making a searchable list app. It will have a 'Filter' button that when clicked, will display a list of filtering options

The modal view controller should come from the right to left, and not cover the whole screen (as seen below).

I have managed to display a view controller programmatically, covering the whole page, but I can't manage to find out how to animate the opening of the view controller (right to left) as well as how to leave some space to see the other View Controller. It must be in Swift. I have seen a few questions about this but all the ones I could find used Objective C and deprecated APIs.

Thanks

Example:

eBay app

Upvotes: 3

Views: 5605

Answers (2)

Duncan C
Duncan C

Reputation: 131481

There are no doubt multiple ways to do this.

One way would be to add a "container view" (It's a special view type in the list of objects in IB) into your current view controller and control-drag an embed segue from the container view onto the other view controller scene that you want to host. Place and size your container view where you want it to end up, and add a leading edge constraint that positions it at that position.

When you use a container view and an embed segue the system takes care of all the housekeeping you need to do in order to host a child view controller.

Wire an outlet to the constraint.

In your viewWillAppear method, add screen width - container x to the constraint's constant and call layoutIfNeeded() on the content view to move it off-screen without animation. Save the amount you added to the horizontal constraint in an instance variable.

Then when you want to animate it onto the screen change the constant value on the constraint (subtract the amount you added in viewWillAppear) and call layoutIfNeeded() inside a UIView animateWithDuration:animations: block.

Upvotes: 7

Dylan Reich
Dylan Reich

Reputation: 1430

You could just create a container view and animate that onscreen from right to left.

let containerView = UIView()
    containerView.addSubview(viewController.view)

Upvotes: 0

Related Questions