<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Arty Korzh on Medium]]></title>
        <description><![CDATA[Stories by Arty Korzh on Medium]]></description>
        <link>https://medium.com/@arty-korzh?source=rss-78890329357------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*FvyzYxuE8X8rVH_IjI6cLw@2x.jpeg</url>
            <title>Stories by Arty Korzh on Medium</title>
            <link>https://medium.com/@arty-korzh?source=rss-78890329357------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 16:02:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@arty-korzh/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to add basic drawer menu with Swift 5]]></title>
            <link>https://arty-korzh.medium.com/how-to-add-basic-drawer-menu-with-swift-5-d71df99501cd?source=rss-78890329357------2</link>
            <guid isPermaLink="false">https://medium.com/p/d71df99501cd</guid>
            <category><![CDATA[animation]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Arty Korzh]]></dc:creator>
            <pubDate>Sat, 26 Sep 2020 20:46:24 GMT</pubDate>
            <atom:updated>2020-10-15T05:43:24.698Z</atom:updated>
            <content:encoded><![CDATA[<h4>Using UIViewControllerTransitioningDelegate</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LflEKMQbNi6PfJJQJ--1OQ.png" /></figure><p>Similar tasks are often faced by iOS developers, especially if they work on outsourcing projects or as a freelancer. There are a bunch of solutions across the internet and I’m going to introduce the solution that I have been used already in multiple projects. So let’s dive in.</p><p>Start with an empty project. For demo purposes, I’m gonna use the Main storyboard as a start point. Then add navigation bar with left navigation bar button to our ViewController. I’ve chosen system image named “text.justify” as it almost looks like burger menu icon</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UNwmX0uMPWgK3oXCa0b5mA.png" /></figure><p>Then add related <em>@IBAction </em>to this bar button menu in <strong>ViewController.swift</strong>. You will finish with something like this</p><pre>@IBAction func didTapMenu(_ sender: Any) {        <br>}</pre><p>But what we gonna do in this action? My solution is just to present a new controller. Yeah, right now it’s not looking like what we need, but have a little patience</p><p>Let’s add another controller called <strong>DrawerMenuViewController</strong>. But first let’s add little bit of structure into our code. Let’s add folder called <strong>DrawerMenu</strong> and add one nested folder called <strong>DrawerMenuController</strong>. Finally create new ViewController by pressing Ctrl+N and select <strong>Cocoa Touch Class</strong>. I prefer to use separate xib files for each new ViewController so i’ve checked <em>Also create XIB file</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PkBQiHQ-fQXIbHtizOXVwg.png" /></figure><p>Now your project should look like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*q_xEhQlprLV9KTQYcAcveg.png" /></figure><p>We ain’t gonna stop on the content of this controller. I’ve just changed the background color so we can see how our drawer controller is shown in the app</p><p>Let’s back to IBAction that we’ve created earlier. Add code to present new controller.</p><pre>// ViewController.swift</pre><pre>@IBAction func didTapMenu(_ sender: Any) {        <br>    let drawerController = DrawerMenuViewController()        <br>    present(drawerController, animated: true)    <br>}</pre><p>Since I use XIB file for this controller, I can simply instantiate it with the base init function. And this is all the code we need in this class.</p><p>If we run the app now and press the menu button we will see basic presenting animation from bottom to top with squashing underlying view. This is definitely not what we need to achieve. So let’s go deeper</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/362/1*SN-hNVi9ncI0Jvv4TuSLqA.gif" /></figure><p>Create a new folder under DrawerMenu called DrawerTransitionManager. Here will be stored all the files responsible for displaying our drawer in the correct manner. Next, create a file called DrawerTransitionManager in this folder choosing Swift File as a source.</p><pre>// DrawerTransitionManager.swift</pre><pre>import UIKit </pre><pre>class DrawerTransitionManager: NSObject, UIViewControllerTransitioningDelegate {<br>}</pre><p><strong>UIViewControllerTransitioningDelegate </strong>class responsible for presenting and animating controllers presented by others</p><p>First, we need to provide this class as transitioningDelegate to presenting controller, in our case DrawerMenuViewController. Open DrawerMenuViewController.swift and create new variable transitionManager that contains DrawerTransitionManager. It’s important to store manager as a variable because transitionDelegate is a weak variable and will be unassigned until your controller will be dismissed, and it will cause problems with animation later.</p><p>Next, create custom init function where we will customise the behaviour of the newly presented controller. It’s required to call super.init(nibName: nil, bundle: nil) inside this custom init. After that add few lines of code to change <em>modalPresentationStyle</em> and assign new <em>transitioningDelegate</em></p><pre>// DrawerMenuViewController.swift</pre><pre>// store transition manager inside view controller class<br>let transitionManager = DrawerTransitionManager()     </pre><pre>init() {        <br>    super.init(nibName: nil, bundle: nil) <br>  <br>// it&#39;s important to set presentation style to custom<br>// because it allows us to modify the presentation later on<br>    modalPresentationStyle = .custom        </pre><pre>    transitioningDelegate = transitionManager    <br>}</pre><pre>// since we provide custom initialiser<br>// we have to provide required init function <br>required init?(coder: NSCoder) {        <br>    fatalError(&quot;init(coder:) has not been implemented&quot;)    <br>}</pre><p>But this is not enough to create drawer animation as we expect it to be. Return to <strong>DrawerTransitionManager </strong>and start writing first function. XCode autocomplete will help you</p><pre>// DrawerTransitionManager.swift</pre><pre>func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -&gt; UIPresentationController?</pre><p>It requires us to create this presentation controller. Create new file in the same folder named DrawerPresentationController by selecting <em>Cocoa Touch Class </em>and set it as subclass of UIPresentationController</p><pre>// DrawerPresentationController.swift</pre><pre>import UIKit </pre><pre>class DrawerPresentationController: UIPresentationController {</pre><pre>// define default size of child controller <br>// inserted in this container controller<br>    override func size(forChildContentContainer container: UIContentContainer, withParentContainerSize parentSize: CGSize) -&gt; CGSize {        <br>        // I want to have some space to the right of drawer <br>        // to see underlying controller<br>        return CGSize(width: parentSize.width * 0.8, height: parentSize.height)    <br>    }     </pre><pre>// define final frame of presented controller<br>// will be set at the end of animation<br>    override var frameOfPresentedViewInContainerView: CGRect {        <br>        var frame: CGRect = .zero        <br>        guard let containerView = containerView else {              <br>            return frame        <br>        }        <br>        frame.size = size(forChildContentContainer: presentedViewController, withParentContainerSize: containerView.bounds.size)        <br>        return frame    <br>    }     </pre><pre>// set final frame to controller at the begin of layouting <br>    override func containerViewWillLayoutSubviews() {        <br>        presentedView?.frame = frameOfPresentedViewInContainerView    <br>    }<br>} </pre><p>Now we can return our presentation controller in manager class</p><pre>// DrawerTransitionManager.swift</pre><pre>func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -&gt; UIPresentationController? {        <br>    return DrawerPresentationController(presentedViewController: presented, presenting: presenting)    <br>}</pre><p>If we run the app now and press the menu button we will still see the wrong animation. But our drawer controller will take only 80% of screen width.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/362/1*vXd_AN0_CJNGFQO-IBVvfg.gif" /></figure><p>Let’s create the correct animation. In our manager, we also have two functions responsible for animation. One for presenting and one for dismissing. You can set different animation for those processes. But we will create the same animation but in different directions.</p><pre>// DrawerTransitionManager.swift</pre><pre>func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -&gt; UIViewControllerAnimatedTransitioning? {<br>}     </pre><pre>func animationController(forDismissed dismissed: UIViewController) -&gt; UIViewControllerAnimatedTransitioning? {<br>}</pre><p>As you can see we need to return something conforms <strong>UIViewControllerAnimatedTransitioning</strong>. First, create a new file at the same folder called <strong>DrawerSlideAnimation</strong>, it is also a simple Swift file.</p><pre>// DrawerSlideAnimation.swift</pre><pre>import UIKit </pre><pre>class DrawerSlideAnimation: NSObject, UIViewControllerAnimatedTransitioning {<br>}</pre><p>It requires two functions: one for duration of animation and one directly for animation</p><pre>// DrawerSlideAnimation.swift</pre><pre>func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -&gt; TimeInterval {        <br>// let&#39;s decide drawer will be sliding during half of a second<br>    return 0.5    <br>}     </pre><pre>func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {<br>// magic happens here<br>}</pre><p>Also to define direction add new public variable to this class, that will be changed depends on the process.</p><pre>// DrawerSlideAnimation.swift</pre><pre>var isPresenting: Bool = true</pre><p>Let’s create our slide animation.</p><pre>// DrawerSlideAnimation.swift</pre><pre>func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {         <br>// if presenting drawer will be under key .to<br>// if dismissing drawer will be under key .from<br>  let key: UITransitionContextViewControllerKey = isPresenting ? .to : .from        </pre><pre>// check if our controller exist in transition<br>    guard let presentedController = transitionContext.viewController(forKey: key) else {            <br>        return        <br>}</pre><pre>// for convenience set containerView to new variable         <br>    let containerView = transitionContext.containerView        </pre><pre>// define position and size of drawer at the end of presentation<br>    let presentedFrame = transitionContext.finalFrame(for: presentedController)        </pre><pre>// define position and size of drawer at the end of dismiss <br>// just offset presentedFrame by its width to left<br>  let dismissedFrame = presentedFrame.offsetBy(dx: -presentedFrame.width, dy: 0)         </pre><pre>// if we are going to present controller, we need to add its view to the container<br>    if isPresenting {            <br>        containerView.addSubview(presentedController.view)        <br>    }         </pre><pre>// get actual duration for animation, defined in the function above<br>    let duration = transitionDuration(using: transitionContext)        </pre><pre>// we need to notify that transition is finished with status from the context, not our custom animation <br>    let wasCancelled = transitionContext.transitionWasCancelled         </pre><pre>// define start and end frames for animation<br>    let fromFrame = isPresenting ? dismissedFrame : presentedFrame        <br>    let toFrame = isPresenting ? presentedFrame : dismissedFrame         </pre><pre>// set start frame for controller view before animation <br>    presentedController.view.frame = fromFrame         </pre><pre>    UIView.animate(withDuration: duration) {            <br>// change controller view frame to end frame during animation<br>      presentedController.view.frame = toFrame        <br>    } completion: { (_) in            <br>// notify animation complete with context status<br>        transitionContext.completeTransition(!wasCancelled)        <br>    }    <br>}</pre><p>That was the hardest and most important part. Now we need to provide this animation to our manager. Since the animation class is the same for both processes I prefer to put it in the variable and change only direction defining variable.</p><pre>// DrawerTransitionManager.swift</pre><pre>let slideAnimation = DrawerSlideAnimation()</pre><pre>func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -&gt; UIViewControllerAnimatedTransitioning? {        <br>    slideAnimation.isPresenting = true        <br>    return slideAnimation    }    </pre><pre>func animationController(forDismissed dismissed: UIViewController) -&gt; UIViewControllerAnimatedTransitioning? {        <br>    slideAnimation.isPresenting = false        <br>    return slideAnimation    <br>}</pre><p>That’s it. Now you can run the app and see that drawer moving from left to right as it supposed to do.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/362/1*3FOO3Fgfb30oZXP_WHAQTQ.gif" /></figure><p>Your final structure should look like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/1*hl3uVlRz9VpdHeIfsWQQfw.png" /></figure><p>But there are a few problems left. We have a transparent space to the right of the drawer and we have no opportunity to close this drawer. Let’s fix this.</p><p>In the presentation controller create semitransparent dimming view, that will cover underlying view.</p><pre>// DrawerPresentationController.swift</pre><pre>private lazy var dimmingView: UIView = {        <br>    let view = UIView()        <br>    view.backgroundColor = UIColor.black.withAlphaComponent(0.5)        <br>    view.translatesAutoresizingMaskIntoConstraints = false        <br>    view.alpha = 0         <br>    return view    <br>}()</pre><p>I prefer lazy initializers for code base views. It’s just my preference. You can use an optional variable and instantiate it before displaying, it’s up to you.</p><p>Now we can use two methods to show and hide our dimming view depends on the transaction process.</p><pre>// DrawerPresentationController.swift</pre><pre>override func presentationTransitionWillBegin() {      <br>    guard  let containerView = containerView else {            <br>        return        <br>    }</pre><pre>// before presentation<br>// add dimmingView to container view beneath presentedController        <br>    containerView.insertSubview(dimmingView, at: 0) </pre><pre>// set constraints of dimming view to fit container<br>// that&#39;s why we set translatesAutoresizingMaskIntoConstraints to false<br>    NSLayoutConstraint.activate([            <br>        dimmingView.topAnchor.constraint(equalTo: containerView.topAnchor),<br>        dimmingView.bottomAnchor.constraint(equalTo: containerView.bottomAnchor),            <br>        dimmingView.leadingAnchor.constraint(equalTo: containerView.leadingAnchor),            <br>        dimmingView.trailingAnchor.constraint(equalTo: containerView.trailingAnchor)        <br>    ])         </pre><pre>// check for animation coordinator<br>// if it&#39;s missing make dimming view visible immediately <br>   guard let coordinator = presentedViewController.transitionCoordinator else {            <br>        dimmingView.alpha = 1            <br>        return        <br>    }        </pre><pre>// otherwise do it in animation <br>// duration of this animation same as duration of slide animation</pre><pre>   coordinator.animate { (_) in            <br>        self.dimmingView.alpha = 1        <br>    }    <br>}</pre><pre>override func dismissalTransitionWillBegin() {   </pre><pre>// do the same for making dimming view transparent on dismiss     <br>    guard let coordinator = presentedViewController.transitionCoordinator else {            <br>        dimmingView.alpha = 0           <br>        return       <br>    }       <br> <br>    coordinator.animate { (_) in            <br>        self.dimmingView.alpha = 0       <br>    } <br>}</pre><p>Now you will see the semitransparent dark background, that fade in and fade out alongside sliding animation. But we still can’t close the drawer. The solution is to add <strong>UITapGestureRecognizer</strong> to the dimming view and on tap hide drawer.</p><pre>// DrawerPresentationController.swift</pre><pre>private lazy var dimmingView: UIView = {        <br>    let view = UIView()        <br>    /// ...<br>    let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(dismissPresentedController))           <br>    view.addGestureRecognizer(tapRecognizer)        <br>    <br>    return view    <br>}()</pre><pre>@objc private func dismissPresentedController() {        <br>    presentedViewController.dismiss(animated: true)    <br>}</pre><p>And that’s all for the most basic drawer for your apps. You can add layout to the drawer controller the same as always, it will be correctly resized to 80% of width in this case according to autolayout rules.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/362/1*FKzPuDpT9MzWz4zPhgtJfg.gif" /><figcaption>Final result</figcaption></figure><p>Full code available on <a href="https://github.com/arty-korzh/drawerMenu/tree/UIViewControllerTransitioningDelegate">GitHab</a></p><h4>Where to go from here?</h4><ul><li>You can create a delegate protocol for the drawer to communicate between ViewController and DrawerController for proper navigation.</li><li>You can change left-side drawer to the right-side by changing dismissedFrame offset by positive width value and moving the origin of frameOfPresentedViewInContainerView to 0.2 of screen width on X axis</li><li>You can improve animation inside DrawerSlideAnimation with easing, by adding and animating other views that make your app stun user with wow-effect</li><li>You can use this knowledge about UIPresentingController and UIViewControllerAnimatedTransitioning to create your own presentable controllers with custom animation</li></ul><p>Thanks for reading. Fell free to leave comments, I appreciate any feedback</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d71df99501cd" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>