<?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 Arjun Baru on Medium]]></title>
        <description><![CDATA[Stories by Arjun Baru on Medium]]></description>
        <link>https://medium.com/@arjun.baru2?source=rss-db1644e99a6c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Y-Ll96oQ0UnjFQzeAnWprA@2x.jpeg</url>
            <title>Stories by Arjun Baru on Medium</title>
            <link>https://medium.com/@arjun.baru2?source=rss-db1644e99a6c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 05:06:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@arjun.baru2/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[All About iOS Animations (Part 1)]]></title>
            <link>https://medium.com/better-programming/all-about-ios-animations-part-1-d49a021527?source=rss-db1644e99a6c------2</link>
            <guid isPermaLink="false">https://medium.com/p/d49a021527</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[ux]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[mobile]]></category>
            <dc:creator><![CDATA[Arjun Baru]]></dc:creator>
            <pubDate>Wed, 09 Dec 2020 23:24:47 GMT</pubDate>
            <atom:updated>2020-12-10T08:56:21.968Z</atom:updated>
            <content:encoded><![CDATA[<h4>A deep dive into KeyFrameAnimation in iOS</h4><figure><img alt="A reel of film" src="https://cdn-images-1.medium.com/max/1024/0*byEOqtuvv5SD_hrW" /><figcaption>Photo by <a href="https://unsplash.com/@dmjdenise?utm_source=medium&amp;utm_medium=referral">Denise Jans</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Overview</h3><p>An outstanding app is all about a top-notch UX, interactive animations, and micro-interactions. In this series, we will discuss different ways to animate views in an iOS application. This is <strong>Part 1 </strong>of the series, We will look into <a href="https://developer.apple.com/documentation/uikit/uiview/1622552-animatekeyframes">KeyFrameAnimation</a> and will implement a small use case.</p><h3>What’s on the Plate Today</h3><p>To understand better, let me give you a gist of what are we trying to replicate.</p><figure><img alt="Screen capture" src="https://cdn-images-1.medium.com/max/334/1*NdsYu6Snax_iyCjz5vWt-w.gif" /><figcaption><em>This is the animation from a popular Wealth Management app</em><strong><em> </em></strong><a href="https://apps.apple.com/us/app/paytm-money-stocks-trading-app/id1344431352"><strong><em>Paytm Money</em></strong></a><strong><em>.</em></strong></figcaption></figure><p>Points to take:</p><ol><li>The top three views look like chained animations as they pile up to make a stack of views.</li><li>The three-dot button transforms into a cross button.</li></ol><p>This looks like an eligible candidate for an animateKeyFrame animation.</p><h3>Prerequisites:</h3><ol><li>You should know about the basics of UIView, frame, and layer.</li><li>You should know about simple animation techniques by tweaking constraints or transforming views.</li></ol><h3>Getting Started</h3><p>Download the project <a href="https://github.com/arjunbaru/KeyFrameAnimationDemo">here</a>.</p><p>What we have here is a View Controller which has three views (topView, middleView, bottomView) fixed at the bottom right corner. These views are inside a stackView(vStackView).</p><p>We have a dotButton placed below the stackView fixed to bottom right.</p><p>When the view loads, we are transforming the views to the right most side from its actual position.</p><p>We have a helper enum Position to transform our views from right to left and vice versa.</p><pre>enum Position {</pre><pre>case reset<br>case rightAligned</pre><pre>func  transform(view: UIView) -&gt; CGAffineTransform {</pre><pre>switch self {<br>case .reset: return .identity<br>case .rightAligned:<br>return CGAffineTransform(translationX: view.frame.maxX + 100, y: 0)</pre><pre>   }<br> }<br>}</pre><p>Before we implement the animation, let’s look into what keyframe animation offers and when to use it.</p><h3>animateKeyframes:</h3><p>UIKit offers a light way to animate views with a UIView.animate() method. We define a block that can be executed for a certain duration. But if we have to chain animations, we have to nest blocks of animating code.</p><p>Luckily, UIView ships with one more method which can solve this clean code problem and has much more advantage.</p><pre>class func animateKeyframes(withDuration duration: <a href="https://developer.apple.com/documentation/foundation/timeinterval">TimeInterval</a>, <br>                      delay: <a href="https://developer.apple.com/documentation/foundation/timeinterval">TimeInterval</a>, <br>                    options: <a href="https://developer.apple.com/documentation/uikit/uiview">UIView</a>.<a href="https://developer.apple.com/documentation/uikit/uiview/keyframeanimationoptions">KeyframeAnimationOptions</a> = [], <br>                 animations: @escaping () -&gt; <a href="https://developer.apple.com/documentation/swift/void">Void</a>, <br>                 completion: ((<a href="https://developer.apple.com/documentation/swift/bool">Bool</a>) -&gt; <a href="https://developer.apple.com/documentation/swift/void">Void</a>)? = nil)</pre><p>You can read about the parameters from the <a href="https://developer.apple.com/documentation/uikit/uiview/1622552-animatekeyframes">apple documentation</a>. We will be focusing on the animation parameter which is a type of closure.</p><h3><strong>Implementing Show Button:</strong></h3><p>We will do the following things on tap of dotButton —</p><ol><li>We will <strong>animate</strong> top, middle and bottom view from right to left side.</li><li>We will <strong>rotate</strong> out dotButton , decrease its alpha from 1 to 0, and finally hide it.</li><li>We will <strong>un-hide</strong>, <strong>rotate</strong> and increase <strong>alpha </strong>with the crossButton placed on top of dotButton.</li></ol><p>Add a target function to dotButton like below:</p><pre>@objc func onTapOfDotButton() {<br>showOptions()<br>}</pre><p>Now, let’s implement the showOptions function. Implement the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/724cc44d5115ec482aa648a677ec8846/href">https://medium.com/media/724cc44d5115ec482aa648a677ec8846/href</a></iframe><p>Let’s understand the points mentioned above.</p><p>//1 We unhide the crossButton which has an alpha of 0 at this point.</p><p>//2 We have an animateKeyframes method which will produce the animation of 0.5 seconds and with 0 delay.</p><p>//3 we add our first set of chained animations via the addKeyframe method. Let’s look at its parameters:</p><p><strong>withRelativeStartTime</strong>: We gave it to 0/0.5, this is the way of saying this internal animation should start just at the beginning of the total duration of animation we have.</p><p><strong>relativeDuration</strong>: We gave it 0.3/0.5, this is the way of saying that to what extend our block should animate with respect to the total time available with us.</p><p><strong>animations</strong>: Inside this block, we <strong>transformed</strong> our bottomView to its initial position (to what we gave constraints, fixing it to bottom right).</p><p>//4 &amp; //5 We followed the same steps as what we did for bottomView explained in step //3. The only change is in //4 <strong>startTime</strong> is 0.1/0.5 and //5 <strong>startTime</strong> is 0.2/0.5 which gives a delay of 0.1 seconds for both the views to animate, thus helping to create the desired effect.</p><p>//6 This block of code handles rotation animation for our dotButton and crossButton. The animation will start with a delay of 0.2 seconds, thus relativeStartTime is 0.2/0.5 and animation duration is 0.3/05. Inside the block we are rotating dotButton and crossButton to an angle of -PI (create anti-clockwise rotation) and changing the alpha of both the buttons. As both of these buttons&#39; animations is in the same block it gives us our desired transformation effect.</p><h3>Implementing the Hide Button:</h3><p>We will do the opposite of what we did in the above implementation.</p><ol><li>We will <strong>animate</strong> top, middle, and bottom view from left to right.</li><li>We will <strong>rotate</strong> out crossButton, decrease its alpha from 1 to 0, and finally hide it.</li><li>We will <strong>un-hide</strong>, <strong>rotate,</strong> and increase <strong>alpha</strong> on the dotButton.</li></ol><pre>@objc func onTapOfCrossButton() {<br>   hideOptions()<br>}</pre><p>Now, let’s implement hideOptions function. Use the below code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/68f3e122e771d5517bdba9b2552533b0/href">https://medium.com/media/68f3e122e771d5517bdba9b2552533b0/href</a></iframe><p>hideOptions has similarities with the showOptions method. The difference is we started with the topView‘s animation towards the right side first, followed by other views.</p><p>Also, the rotation for crossButton and dotButton is in PI to create a clockwise rotation effect.</p><h3>Result:</h3><p>Build and run:</p><figure><img alt="example animation" src="https://cdn-images-1.medium.com/max/304/1*Hzpn9JC-BBGBsui0oAUXZA.gif" /><figcaption>Example animation</figcaption></figure><p>Awesome!<em> </em>We learned about the keyframe animation which helps to chain animating views. Next,<strong> </strong>we will learn about basicAnimation in Part-2 of this tutorial series.</p><h3>Also See:</h3><ul><li><a href="https://medium.com/better-programming/building-a-custom-transitioning-for-viewcontroller-in-ios-13-cbf9b4de3d9b">Building a Custom Transitioning for ViewController in iOS 13+</a></li><li><a href="https://medium.com/swlh/creating-youtube-style-loading-animation-d30b465ce0ca">Creating Youtube Style Loading Animation</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d49a021527" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/all-about-ios-animations-part-1-d49a021527">All About iOS Animations (Part 1)</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating Youtube Style Loading Animation]]></title>
            <link>https://medium.com/swlh/creating-youtube-style-loading-animation-d30b465ce0ca?source=rss-db1644e99a6c------2</link>
            <guid isPermaLink="false">https://medium.com/p/d30b465ce0ca</guid>
            <category><![CDATA[ui-design]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[animation]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Arjun Baru]]></dc:creator>
            <pubDate>Tue, 25 Aug 2020 06:17:52 GMT</pubDate>
            <atom:updated>2020-08-26T11:13:52.984Z</atom:updated>
            <content:encoded><![CDATA[<p>Custom loading animation for you apps</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NtPzBo56Q54Tbm0v" /><figcaption>Photo by <a href="https://unsplash.com/@ikasalovic?utm_source=medium&amp;utm_medium=referral">Igor Kasalovic</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Overview</h3><p>In this tutorial we will be building a shimmer animation which can be used as a placeholder view for time when your app is busy fetching data through API or some background process.</p><p>This type of loading was introduced by <strong>Facebook</strong> and now commonly seen in apps like <strong>Youtube</strong> and <strong>Instagram</strong> as well.</p><p>If you want your app to stand out, this is the new normal.</p><h3>What are we building ?</h3><p>A custom animation view, which can act like a placeholder till the time API returns response.</p><p>Our final product will look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/264/1*VpsTZIch8cQH9YwsP2exvw.gif" /><figcaption>Note: GIF’s have quality limitations.</figcaption></figure><h3>Getting Started</h3><p>Download the Final Project from <a href="https://github.com/arjunbaru/ShimmerLoadingDemo">here</a>.</p><p>Let’s look into the project. For creating shimmer effect we will be working with <a href="https://developer.apple.com/documentation/quartzcore/cagradientlayer">GradientLayer</a> and <a href="https://developer.apple.com/documentation/quartzcore/cabasicanimation">CABasicAnimation</a></p><p>Extend UIView and add the below code:</p><pre>extension UIView {<br>func applyShimmerEffect() {</pre><pre>//1</pre><pre>let light = backgroundColor?.withAlphaComponent(0.5).cgColor ?? UIColor(red: 0, green: 0, blue: 0, alpha: 0.1).cgColor</pre><pre>let dark = UIColor.clear.cgColor</pre><pre>let shimmerGradientLayer = CAGradientLayer()</pre><pre>shimmerGradientLayer.colors = [light, dark]</pre><pre>shimmerGradientLayer.frame = CGRect(<br>x: -bounds.width,<br>y: 0,<br>width: 50 * bounds.size.width,<br>height: bounds.size.height<br>)</pre><pre>shimmerGradientLayer.startPoint = CGPoint(x: 0.0, y: 0)<br>shimmerGradientLayer.endPoint = CGPoint(x: 1.0, y: 0)<br>shimmerGradientLayer.locations = [0.0, 0.1]<br>layer.mask = shimmerGradientLayer</pre><pre>//2</pre><pre>let animation = CABasicAnimation(keyPath: &quot;locations&quot;)</pre><pre>animation.fromValue = [0.0, 0.1]</pre><pre>animation.toValue = [0.1, 0.2]</pre><pre>animation.duration = 0.7</pre><pre>animation.repeatCount = Float.infinity</pre><pre>animation.autoreverses = true</pre><pre>shimmerGradientLayer.add(animation, forKey: &quot;shimmer&quot;)</pre><pre>}</pre><pre>}</pre><p>//1 We will start with creating two colours for our gradient layer. First one is Light which has colour of view with alpha of 0.5, second is a clear colour.</p><p>Create a gradient layer, add the above colours to it. Set the frame of gradient to something bigger in larger in width and placed at the a position -bounds.width .This is done to give a pulse effect when we animate the layer.</p><p>Our gradient should animate along xaxis so the start and end points are given accordingly.</p><p>location property of the gradient is animatable. We will be changing the location property to produce animation.</p><p>//2 Create a CABasicAnimation instance. We will provide toValue and fromValue to the instance, toValue should be the location property set by our gradient layer and fromValue can be according to our animation.</p><p>We are setting the repeat count to infinity as our motive is to show the animation until API returns the response. Also, to make the animation smooth and have a pulse effect, we will set autoreverses = true .</p><p>This is all we need to create a shimmer effect. Next step. Creating s<strong>himmer Cards.</strong></p><h3>Card View:</h3><p>We will need a protocol Shimmerable for creating shimmer cards, add the following code —</p><pre>protocol Shimmerable: UIView {</pre><pre>var shimmerViews: [UIView] { get }</pre><pre>}</pre><pre>extension Shimmerable {</pre><pre>func loadShimmer() {</pre><pre>shimmerViews.forEach { $0.applyShimmerEffect() }</pre><pre>}</pre><p>Our card view will conform to this protocol, and will provide it the views on which shimmer needs to be applied.</p><blockquote><strong>Note</strong>: Our shimmer card is something which will be shown during API call. It is a placeholder which will be displayed till the time data is fetched.</blockquote><p>Let’s create a shimmer view card, Add the following class and we will go step by step to understand it.</p><pre>final class ShimmerView: UIView {</pre><pre>override init(frame: CGRect) {<br>super.init(frame: frame)<br>commonInit()<br>backgroundColor = .clear<br>}</pre><pre>required init?(coder: NSCoder) {<br>fatalError(&quot;init(coder:) has not been implemented&quot;)</pre><pre>}</pre><pre>//1<br>private let titleView: UIView = {<br>let view = UIView()<br>view.layer.cornerRadius = 5<br>view.width(160)<br>view.height(25)<br>view.backgroundColor = .lightGray<br>return view<br>}()</pre><pre>private let descriptionView: UIView = {<br>let view = UIView()<br>view.layer.cornerRadius = 5<br>view.width(UIScreen.main.bounds.width * 0.80)<br>view.height(150)<br>view.backgroundColor = UIColor.red.withAlphaComponent(0.5)<br>return view<br>}()</pre><pre>}</pre><pre>//2<br>extension ShimmerView {</pre><pre>func commonInit() {<br>setupUI()<br>setConstraints()<br>}</pre><pre>func setupUI() {<br>addSubview(titleView)<br>addSubview(descriptionView)<br>}</pre><pre>func setConstraints() {<br>titleView.leadingToSuperview(offset: 15)<br>titleView.topToSuperview(offset: 15)<br>descriptionView.leadingToSuperview(offset: 15)<br>titleView.bottomToTop(of: descriptionView, offset: -12)<br>}<br>}</pre><pre>//3<br>extension ShimmerView: Shimmerable {<br>  public var shimmerViews: [UIView] {<br>    return [titleView, descriptionView]<br>   }<br>}</pre><p>//1 We have created a ShimmerView class which is subclasses of UIView . We have add two views, title and description , on which we will be applying the shimmer effect.</p><p>//2 this extension just adds the view to superView and align them one below the other.</p><p>//3 We will now conform to protocol Shimmerable and provide the views to which we will be adding shimmer effect, in our case, title and description view.</p><p>Let’s add and connect this view to our ViewController . Open ViewController.swift and add the following code in viewDidLoad method—</p><pre>override func viewDidLoad() {</pre><pre>super.viewDidLoad()</pre><pre>view.addSubview(shimmerView)<br>shimmerView.topToSuperview(offset: 20, usingSafeArea: true)<br>shimmerView.width(UIScreen.main.bounds.width)<br>shimmerView.centerXToSuperview()</pre><pre>DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {<br>self.shimmerView.loadShimmer()<br>   }<br>}</pre><p>Build and Run ! Also, let’s see how it looks in <strong>Dark Mode.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/266/1*BZvG7z_kNPX67JLBqUlG2w.gif" /><figcaption>Note: GIF’s have quality limitations.</figcaption></figure><p>Awesome !! We have a placeholder for our content now and we got rid of our traditional loading style. Do you know, SwiftUI has an <strong>in-build</strong> placeholder for its properties ? well that’s a good topic for another animation tutorial.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d30b465ce0ca" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/creating-youtube-style-loading-animation-d30b465ce0ca">Creating Youtube Style Loading Animation</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Build a Navigator to Go to Any Page You Want in Swift]]></title>
            <link>https://medium.com/better-programming/how-to-build-a-navigator-to-go-to-any-page-you-want-in-swift-ae14ef6ba4ee?source=rss-db1644e99a6c------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae14ef6ba4ee</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[mobile]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Arjun Baru]]></dc:creator>
            <pubDate>Thu, 16 Jul 2020 12:48:18 GMT</pubDate>
            <atom:updated>2020-07-17T06:46:19.678Z</atom:updated>
            <content:encoded><![CDATA[<h4>Navigate to different view controllers as per server data or a sequence</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HuTRm7ehZxSKoI_O" /><figcaption>Photo by <a href="https://unsplash.com/@nicolerwilcox?utm_source=medium&amp;utm_medium=referral">Nicole Wilcox</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Overview</h3><p>Let’s try to build a navigation manager that will help us to navigate to any view controller where the presented view controller does not have a concrete implementation of the next step.</p><p>This type of approach can be used for an onboarding flow for a new user or filling of forms, where the user has to complete a sequence of steps.</p><p>Also, this approach is future-proof. If your flow changes or product requirements change, you just have to do a couple of changes to get it working.</p><h3>Prerequisite</h3><p>Basics of Swift and a good understanding of protocols and enums.</p><h3>Get Started</h3><p>Download the starter project from <a href="https://github.com/arjunbaru/AnyPageNavigation">here</a>.</p><p>Let’s explore the starter project. Open Main.storyboard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mcVeB7o-FGQg_K_XSEs0AQ.png" /><figcaption>Image source: Author</figcaption></figure><p>We have five view controllers with different colours and a button with the title Next Colour. By tapping the button in a view controller, we should push a new view controller.</p><p>The pattern is undefined, which means that the next colour in the step will be defined by a third party (just as we receive steps from the server on completing a particular flow).</p><p>Open the AllColourViewController.swift file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3yFLC4BasL79keJjNtCIoQ.png" /></figure><p>Just like RedViewController, there is a class for every other colour, with an action button in place.</p><p>Let’s build a navigator that’s robust and scalable for sequential navigation.</p><h3>Let’s Build</h3><p>Start by adding a fileCustomNavigator.swift.</p><p>Let’s study a few concepts which will be pillars of this implementation. Add the following code:</p><pre>struct Step {</pre><pre>let guider: NextStepGuider<br>let validator: NextStepValidator</pre><pre>}</pre><p><strong>Step</strong></p><p>Step is something that has two properties, NextStepGuider and NextStepValidator . Step has information about the current step in the process, and it validates whether to execute it or not.</p><p>Consider it as something like Link List, which contains the address of the next node and a data/value.</p><p><strong>Guider </strong><strong>NextStepGuider</strong></p><p>A guider should be something which will give us our next step getNextStep(). Also, it should be able to route to a view controller for the currently selected step.</p><pre>protocol NextStepGuider {</pre><pre>func routeToViewController()<br>func getNextStep() -&gt; NextStepGuider?</pre><pre>}</pre><p>In our case, I am using an enum as a guider. Let’s understand the below code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3tFooFTjEqNXLjp1_-czCw.png" /></figure><p>//1 We can switch over to enum to guide to the particular view controller.</p><p>//2 This function knows the next step in the process and will return the type NextStepGuider (itself) so that the next page should be able to load the view controller by calling the routeToViewController function.</p><p>This is similar to Link List, where node contains the address of the next node.</p><p>Also, I’m using a helper function pustToTopMostViewController to get the UINavigationController and push the ViewController to that stack.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/02ed2cdd9ecd632eb935399c9fde8aba/href">https://medium.com/media/02ed2cdd9ecd632eb935399c9fde8aba/href</a></iframe><p><strong>Validator </strong><strong>NextStepValidator</strong></p><pre>public protocol NextStepValidator {<br>func shouldMoveForward() -&gt; Bool<br>}</pre><p>This will help us to validate whether to proceed for that step based on some validation. Consider a scenario where you will only proceed to that page if the status of that step is Pending. We should not see that page if the status is in Progress/Completed .</p><p>Our validator will look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tp7d0ZK5NOBC66VrlfjH-A.png" /></figure><p>Great, now we have our guider and validator. Our next stop: a manager.</p><h3>SequenceManager</h3><pre>protocol SequenceManager {<br>var sequenceOfSteps: SequenceQueue { get set }<br>func loadInitialViewController()<br>func getNextStepInOnboarding(currentStep: NextStepGuider)<br>}</pre><p>A sequence manager should be able to control the view controller request. A sequence manager will be the one communicating with view controllers.</p><p>The manager will accept all the steps for a particular flow through sequenceOfSteps. Let’s see how SequenceQueue should look.</p><pre>struct SequenceQueue {</pre><pre>let sequenceList: [Step]</pre><pre>func checkForNextStep() -&gt; Step? {</pre><pre>for step in sequenceList {<br>  if step.validator.shouldMoveForward() {<br>     return step<br>     }<br>   }return nil<br>  }<br>}</pre><p>We have the function checkForNextStep which is responsible for validating and returning the step to be navigated to.</p><p>Let’s extend the SequenceManager and add a default behaviour.</p><pre>extension SequenceManager {</pre><pre>func loadInitialViewController() {<br>  sequenceOfSteps.checkForNextStep()?.guider.routeToViewController()<br> }</pre><pre>}</pre><p>In the loadInitialViewController function, we want to iterate through each step, check and validate whether to navigate to that step, and then finally route to its view controller.</p><p>func getNextStepInOnboarding will be the function called by a view controller. This function will let our manager know what step we are on currently and then navigate to the next step. This function will have an explicit implementation as per different managers.</p><h3>Let’s Create a Flow Manage Class</h3><p>Let’s create the singleton class NavigationManager.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o61U0TeLXp03UYGe_YxEHg.png" /></figure><p>//1 We created a singleton by marking class as final, initialising it as private, and using a static property to access a single instance available throughout the life cycle.</p><p>//2 Here we are iterating over the sequenceList with us and validating it with the guider provided by the view controller.</p><p>If the guider matches the one in the list, check for validation by calling shouldMoveForward, and then route to the particular view controller.</p><p>If validation fails, recursively get the next step and do the above step for the new step.</p><p>Let’s connect getNextStepInOnboarding step in our ViewController.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AoPp9usnZ2TrOjE50g-0hA.png" /></figure><p>We will be calling our singleton in the button action. viewController is responsible for telling the current guiding step. Similarly, other view controllers will have this implementation.</p><p>Let’s create a sequence list.</p><p>Add this global function getSequenceOfSteps:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c01dca7af85f2e5b024cd42fc8c4721/href">https://medium.com/media/0c01dca7af85f2e5b024cd42fc8c4721/href</a></iframe><p>As of now, the status of all the functions is pending, so all views should be presented.</p><p>Before we Run, we have to add one more step in the sceneDelegate (iOS 13)/ AppDelegate (lower versions).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MWRBW13k3G8z5rEselEJRA.png" /></figure><p>This will help us to get our first/initial view controller.</p><p>Let’s build!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/318/1*nSXshwiemwtv6lM2x_0Mdw.gif" /></figure><p>Great, let’s try modifying the step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S9GDZAchjS2jGvgb4q04Dw.png" /></figure><p>Now step 1 and step 3 are completed and in progress, respectively. We should only be navigating to step 2, 4, and 5 (i.e., yellow, blue, and brown.)</p><p>Let’s test.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/318/1*A-0BQktCARZlaHd-PgXEOw.gif" /></figure><p>Awesome! We made an any-view-controller router. The only change we have to do is in the manager if the requirement changes. Also, view controllers are loosely coupled with each other.</p><p>This navigator is built keeping in mind that the steps will not change. If the step flow changes, we have to change our NextStepGuider in the same way.</p><h3><strong>Also See:</strong></h3><ul><li><a href="https://medium.com/better-programming/when-to-use-strong-references-over-weak-references-in-swift-6238bf8e58bf">When to Use Strong References Over Weak References in Swift</a></li><li><a href="https://medium.com/better-programming/building-a-custom-transitioning-for-viewcontroller-in-ios-13-cbf9b4de3d9b">Building a Custom Transitioning for ViewController in iOS 13+</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae14ef6ba4ee" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/how-to-build-a-navigator-to-go-to-any-page-you-want-in-swift-ae14ef6ba4ee">How to Build a Navigator to Go to Any Page You Want in Swift</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[When to Use Strong References Over Weak References in Swift]]></title>
            <link>https://medium.com/better-programming/when-to-use-strong-references-over-weak-references-in-swift-6238bf8e58bf?source=rss-db1644e99a6c------2</link>
            <guid isPermaLink="false">https://medium.com/p/6238bf8e58bf</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[mobile]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Arjun Baru]]></dc:creator>
            <pubDate>Wed, 03 Jun 2020 18:03:53 GMT</pubDate>
            <atom:updated>2020-06-03T18:03:53.852Z</atom:updated>
            <content:encoded><![CDATA[<h4>Let’s avoid overusing <em>weak</em><strong> </strong>references</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zXB9cKf1SbT0tIsnMbn30w.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@the_modern_life_mrs?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Heather Ford</a> on <a href="https://unsplash.com/s/photos/be-strong-coffee?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>Overview</h3><p>If we talk about memory leaks, the first thing we rush to check is the retain cycle.<strong> </strong>To avoid this scenario we declare properties or<em> </em>capture<em> </em>self<em> </em>a<em>s </em>weak<em>.</em></p><p>As declaring weak has become our easy get-out — sometimes we start declaring weak even though there’s no retain cycle happening. We’ll discuss few scenarios in which we misinterpret the use case.</p><h3><strong>Retain Cycle</strong></h3><p>Before we start, let’s understand what the retain cycle is and how memory leaks happen.</p><p>Let’s study the retain cycle with an example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EuP1KDVXIn_z7tzwQOU2sQ.png" /></figure><p>We created objects of both the class, First and Second, and made them hold each other’s reference, hence increasing the reference count to 2 each.</p><p>When we try to deallocate memory, deinit was not called because not all the references were removed. Can we release it now? Well no, because they’re inaccessible, causing a memory leak.</p><p>So the memory leak is of the inaccessible memory, which happened when we were unable to deallocate the object.</p><p>We solve this by manually handling the deallocation:</p><pre>/// 1. By manual handling</pre><pre>object1?.secondOne = nil<br>object2?.firstOne = nil</pre><pre>object2 = nil<br>object1 = nil</pre><p>And making one of the properties weak:</p><pre>weak var firstOne: First? // changing line 12</pre><pre>///// 2. By Weak approach</pre><pre>object2 = nil<br>object1 = nil</pre><p>Great — we know how to avoid the retain cycle, but sometimes we misinterpret whether it is actually happening.</p><h3>Four Scenarios Where It’s OK to Be Strong</h3><h4>1. When dealing with view animation.</h4><p>Let’s study the ViewAnimation class:</p><pre>class ViewAnimation {</pre><pre>func viewAnimate() {</pre><pre>// weak self not required below<br>UIView.animate(withDuration: 0.3) { [weak self] in<br>    self?.doSometing()<br>  }<br>}</pre><pre>func doSometing() {}</pre><pre>}</pre><p>You may or may not be using the weak self<em> </em>here, but let’s understand why there’s no memory leak.</p><p>This closure definitely captures the self strongly, but these lines are written inside the function’s body — the class ViewAnimation is <em>not</em> holding the closure strongly .</p><p>ViewAnimation will be deallocated once this closure gets executed, as the animate function will temporarily hold the reference until executed.</p><h4>2. When dealing with DispatchQueue.</h4><p>Let’s add another function to the class — ViewAnimation:</p><pre>func whenDispatchHappens() {</pre><pre>DispatchQueue.main.asyncAfter(deadline: .now() + 20) { [weak self] in<br>  self?.doSometing()<br>  }<br>}</pre><pre>func doSometing() {}</pre><p>This is similar to case 1 discussed above. DispatchQueue scope is local and does not have a stronghold by the class ViewAnimation. So, after closure the execution reference is released — in this case, after 20 seconds.</p><p><strong><em>Note: </em></strong><em>Not all cases of local scope are the same as cases </em><em>1 and </em><em>2. </em><em>NotificationCenter, on the other hand, will not release the </em><em>self once executed. KVO type implementations are different and shouldn’t be confused with these examples.</em></p><h4>3. When dealing with Delegation</h4><p>Yes — not all delegation scenarios, but here’s a case where we play safe.</p><p>Consider a common scenario of Model Presentation, where on the tap of a button,PresentingViewController attempts to present a NewViewController. To talk back to PresentingViewController we generally implement a delegation pattern. Let’s check the example code below:</p><pre>@IBAction func onTapOfShowCities(_ sender: Any) {</pre><pre>guard let vc = UIStoryboard(name: &quot;Main&quot;, bundle: nil)<br>.instantiateViewController(identifier: &quot;NewViewController&quot;) as? NewViewController else { return }</pre><pre>// The below delegate property can declared strong<br>vc.delegate = self</pre><pre>self.present(vc, animated: true, completion: nil)</pre><pre>}</pre><p>Here, NewViewController’s delegate property need not be <em>weak. </em>There’s no retain cycle as PresentingViewController is not holding NewViewController strongly — its scope is local.</p><p>The line self.present(vc, animated: true, completion: nil) — this reference is internally managed by Apple and gets removed on dismissing ViewController.</p><h4>4. When dealing with IBOutlets</h4><p>@IBOutlet weak var showCities: UIButton!</p><p>You may be wondering if Apple’s default, IBOutlets, are weak when dragged and connected.</p><p>Well, it’s just like how Show Blame changed to Author (sentimens get hurt when things change). This is under consideration but may take some time to reflect.</p><p>But, there’s <em>no</em> retain cycle involved with IBOutlets declared as strong.</p><p>Let’s study the diagram below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4k3XBsCBVbOtuwVTAQaZCg.png" /></figure><p>Tt clearly implies that IBOutlet is referenced in two places, view and ViewController. But they’re not forming a dependency cycle (AKA retain cycle).</p><p>Let’s take a look at the view controller deallocation process:</p><ul><li>First View controller will try to deallocate all its subviews and properties.</li><li>view is the one to be released — so view first releases one reference of the IBOutlet.</li><li>Now, as per the ViewControllers deallocation process, the remaining properties are also released, thereby releasing the second reference of IBOutlet.</li></ul><p>As IBOutlet is not holding either the view or ViewController, the retain cycle will not happen.</p><p>Great — I hope we cleared the air. Although weak self is a safety measure, we should be clear with the use cases.</p><h3>Further Discussions on This Topic</h3><ul><li><a href="https://stackoverflow.com/questions/7678469/should-iboutlets-be-strong-or-weak-under-arc">IBOutlets as Strong</a></li><li><a href="https://stackoverflow.com/questions/41991467/where-does-the-weak-self-go">DispatchQueue with Strong self closure</a></li></ul><h3>Some Crazy Implementations</h3><ul><li><a href="https://medium.com/better-programming/building-a-custom-transitioning-for-viewcontroller-in-ios-13-cbf9b4de3d9b">Building a Custom Transitioning for ViewController in iOS 13+</a></li><li><a href="https://medium.com/better-programming/building-an-animating-navigation-bar-in-ios-13-96355c6822ce">Build an Animating UINavigationBar in Swift</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6238bf8e58bf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/when-to-use-strong-references-over-weak-references-in-swift-6238bf8e58bf">When to Use Strong References Over Weak References in Swift</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Custom Transitioning for ViewController in iOS 13+]]></title>
            <link>https://medium.com/better-programming/building-a-custom-transitioning-for-viewcontroller-in-ios-13-cbf9b4de3d9b?source=rss-db1644e99a6c------2</link>
            <guid isPermaLink="false">https://medium.com/p/cbf9b4de3d9b</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[mobile]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Arjun Baru]]></dc:creator>
            <pubDate>Tue, 26 May 2020 16:19:43 GMT</pubDate>
            <atom:updated>2020-06-03T19:18:02.132Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building a Custom Transitioning for ViewController in iOS</h3><h4>Let’s build custom transitions into our appsybill bed</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HGWRGpqh6VoLcgGaqbEqKw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@wesson?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Wesson Wang</a> on <a href="https://unsplash.com/s/photos/mac?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3><strong>Overview</strong></h3><p>Every new iOS comes with design changes. This time we saw the new View Presentation Style,<strong> </strong>which gives a 3D look to a view controller.</p><p>Although Swift is open-source, Apple’s framework isn’t. You might be wondering how apple did it — I certainly was. I’ve discovered that it’s not a black box.</p><p>In this article, we’ll try to recreate what Apple has been cooking — AKA <em>cracking the iOS Code!</em></p><h3><strong>Prerequisites</strong></h3><p>Be familiar with UIViewControllerTransitioningDelegate and UIViewControllerAnimatedTransitioning. If you’re not, you’d better check out this <a href="https://www.raywenderlich.com/322-custom-uiviewcontroller-transitions-getting-started">Ray Wenderlich</a> article first.</p><h3>Getting Started</h3><p><a href="https://github.com/arjunbaru/customTransitioning">Download the project</a>.</p><p>Let’s explore the starter project. Build and run:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/348/1*6CAFvyS7hsRqkY_o1zNM-g.gif" /><figcaption>iOS 13 Presentation</figcaption></figure><p>Looking through the code, we have a PresentingViewController class with the Show Cities button and a PresentedViewController class which shows some city data.</p><p>If you’re wondering how to animate Navigation Bar, check out <a href="https://medium.com/better-programming/building-an-animating-navigation-bar-in-ios-13-96355c6822ce?source=your_stories_page---------------------------">Build an Animating UINavigationBar in Swift</a>.</p><h3><strong>Let’s Code</strong></h3><p>We’ll start by adding CustomAnimatedController.swift to project.</p><p>First, add this helper enum in the file:</p><pre>enum ViewControlerScale {<br>case modelPresentationScale<br>case reset</pre><pre>var transform: CATransform3D {<br>switch self {<br>case .modelPresentationScale:<br>return CATransform3DMakeScale(0.88, 0.88, 1)<br>case .reset:<br>return CATransform3DMakeScale(1, 1, 1) <br>     }<br>  }<br>}</pre><p>This will help us to achieve background shrink when new viewController pops up and reset it once viewController dismiss. You will have a better idea once we use it.</p><p>Now, let’s add the below class:</p><pre>//1<br>class CustomAnimatedController: NSObject, UIViewControllerAnimatedTransitioning {</pre><pre>//2<br>func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -&gt; TimeInterval {}</pre><pre>//3<br>func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {}<br>}</pre><p>//1 We started with creating a CustomAnimatedController which conforms to UIViewControllerAnimatedTransitioning. This delegate has two mandatory methods (2 and 3).</p><p>//2 This function asks for the time duration for the animation.</p><p>//3 This is where we add the magic. This function is responsible for transitioning from current ViewController to future ViewController.</p><p>As per the above understanding, what does this class need? Duration (for delegate), estimated final height, and whether we’re presenting or dismissing the viewController (we’ll come to this part later).</p><p>Add the below code to the class:</p><pre>let estimatedFinalHeight: CGFloat<br>let animationDuration: TimeInterval<br>var isPresenting: Bool</pre><pre>init(estimatedFinalHeight: CGFloat, animationDuration: TimeInterval, isPresenting: Bool) {</pre><pre>self.estimatedFinalHeight = estimatedFinalHeight<br>self.animationDuration = animationDuration<br>self.isPresenting = isPresenting</pre><pre>}</pre><p>Let’s explore func animateTransition(using transitionContext: UIViewControllerContextTransitioning)<em>.</em></p><p>Add the following code:</p><pre>// 1<br>guard let fromVC = transitionContext.viewController(forKey: .from),<br>let toVC = transitionContext.viewController(forKey: .to) else { return }</pre><pre>//2<br>let containerView = transitionContext.containerView</pre><pre>//3<br>fromVC.beginAppearanceTransition(false, animated: true)<br>toVC.beginAppearanceTransition(true, animated: true)</pre><p>//1 This line will give us both the view controllers(to and from).</p><p>//2 The container view is responsible for the animation. We add the view which will be presenting and dismissing to animate it accordingly.</p><p>//3 When we do custom presentation, our viewController’s lifecycle doesn’t get called which will result in abrupt behaviour. It’s recommended that we <em>never </em>call lifecycle methods directly. This function takes care of that.</p><p>Let’s add code in order to present a view controller on top of another:</p><pre>if isPresenting {</pre><pre>// 1<br>toVC.view.frame.origin.y = fromVC.view.frame.maxY<br>containerView.addSubview(toVC.view)</pre><pre>UIView.animate(withDuration: animationDuration, animations: {</pre><pre>// 2<br>toVC.view.frame.origin.y = self.estimatedFinalHeight<br>fromVC.view.layer.transform = <br>ViewControlerScale.modelPresentationScale.transform</pre><pre>}, completion: { _ in</pre><pre>//3<br>fromVC.endAppearanceTransition()<br>toVC.endAppearanceTransition()</pre><pre>transitionContext.completeTransition(!transitionContext.transitionWasCancelled)<br>  })<br>}</pre><p>//1 We will fix the “To be presented” ViewController at the bottom of the currently presented ViewController. Add toVC to Container view(as this is responsible for holding the presented ViewController).</p><p>//2 Within Animation we are changing the Y Axis of toVC from maxY to the desired height. Also, with the help enum, declared above, we transform our background ViewController to scale/shrink to give a 3D effect.</p><p>//3 Once we’re done with animation, we notify system so that lifecycle methods can be called properly.</p><p>If not presenting, it should be dismissing. Let’s add the else part in continuity to the above code:</p><pre>else {</pre><pre>// 1<br>containerView.addSubview(fromVC.view)</pre><pre>UIView.animate(withDuration: animationDuration, animations: {</pre><pre>// 2<br>fromVC.view.frame.origin.y = UIScreen.main.bounds.maxY<br>toVC.view.layer.transform = ViewControlerScale.reset.transform</pre><pre>}, completion: { _ in</pre><pre>// 3<br>fromVC.endAppearanceTransition()<br>toVC.endAppearanceTransition()</pre><pre>transitionContext.completeTransition(!transitionContext.transitionWasCancelled)<br>  })<br>}</pre><p><strong>The catch: </strong>We’re also using the same function to dismiss ViewController. At this time, we’re going from PresentedViewController (which will now be fromVC) to presentingViewController (which will be toVC). The tables have turned!</p><p>//1 We are translating the pop-up ViewController to the bottom before it gets dismissed. This view gets added to containerView.</p><p>//2 Reset the toVC (PresentingViewController) which we scaled down previously to its original scale.</p><p>//3 Let the system know we are done with Animation so that appropriate lifecycle methods get called.</p><h3>Setting up the Transitioning Delegate Class</h3><p>Let’s add another file — CustomTransitioningController.swift — and add the following code to it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3825c9b5ddac34b3d10f04431212d2ad/href">https://medium.com/media/3825c9b5ddac34b3d10f04431212d2ad/href</a></iframe><p>//1 This class will take up the initial heigh and duration which will then be passed to our CustomAnimatedController class. Also, this is the front liner class which will be consumed by our Viewcontrollers.</p><p>//2 We will have a private var animatorController which will be guiding the presentation and dismissal of the view controllers.</p><p>Our CustomTransitioningController class conforms to delegate UIViewControllerTransitioningDelegate , this delegate comes with two optional functions — let’s look at them.</p><pre>// 1<br>func animationController(forPresented presented: UIViewController,<br>presenting: UIViewController,<br>source: UIViewController)<br>-&gt; UIViewControllerAnimatedTransitioning? {</pre><pre>animatorController.isPresenting = true<br>return animatorController</pre><pre>}</pre><pre>// 2<br>func animationController(forDismissed dismissed: UIViewController)<br>-&gt; UIViewControllerAnimatedTransitioning? {</pre><pre>animatorController.isPresenting = false<br>return animatorController</pre><pre>}</pre><p>//1 The first function guides us for the presenting flow. We get presented (our current VC) and presenting (to be presented VC). Any additional changes to viewController before the animation can be done here.</p><p>//2 This function gives us the controller which will be going to dismiss. Any last-minute adjustment can be made to that view in this function.</p><h3>Time to Connect Our Custom Presentation</h3><p>Add a property to the PresentingViewController class:</p><pre>let customTransitioningDelegate = CustomTransitioningController()</pre><p>Replace the body of onTapOfShowCities function with the below code.</p><pre>guard let vc = UIStoryboard(name: &quot;Main&quot;, bundle: nil).instantiateViewController(identifier: &quot;PresentedViewController&quot;) as? PresentedViewController else { return }</pre><pre>vc.modalPresentationStyle = .custom<br>vc.transitioningDelegate = customTransitioningDelegate</pre><pre>self.present(vc, animated: true, completion: nil)</pre><p>We set the presentation style to custom and let the system know about our new transitioning delegate.</p><p>Build and run!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*_oOb820u8UCvsahcO9NVfg.png" /></figure><p>Just as we expected. But wait, why are the corners so sharp? Let’s fix them.</p><p>Go to CustomAnimatedController class and add the following code (mentioned on the breakpoint, line numbers 63 and 77).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EneiYEWmq1jKFIDrpfvHVQ.png" /><figcaption>We are cornering the radius when presenting and reverting at dismissal.</figcaption></figure><h3>The Final Result</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/348/1*XloAQQlAKRkjx617yP2paA.gif" /><figcaption>Custom Presentation.</figcaption></figure><p>Great job! We now have something similar to what Apple has. If you observe Apple’s animation, we see swipe to dismiss and a nice fade to background too. Can we do that? Of course, but that&#39;s a topic for Part 2 of the tutorial!</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cbf9b4de3d9b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/building-a-custom-transitioning-for-viewcontroller-in-ios-13-cbf9b4de3d9b">Building a Custom Transitioning for ViewController in iOS 13+</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build an Animating UINavigationBar in Swift]]></title>
            <link>https://medium.com/better-programming/building-an-animating-navigation-bar-in-ios-13-96355c6822ce?source=rss-db1644e99a6c------2</link>
            <guid isPermaLink="false">https://medium.com/p/96355c6822ce</guid>
            <category><![CDATA[mobile]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Arjun Baru]]></dc:creator>
            <pubDate>Mon, 11 May 2020 18:35:24 GMT</pubDate>
            <atom:updated>2020-05-21T13:17:23.222Z</atom:updated>
            <content:encoded><![CDATA[<h4>Go beyond default navigation bar functionality</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*e_KaILWGWIBG5Ssr" /><figcaption>Photo by <a href="https://unsplash.com/@ryz0n?utm_source=medium&amp;utm_medium=referral">Ryan Tang</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a>.</figcaption></figure><h3>What Are We Building?</h3><p>We will be building a custom navigation bar that has an animating view and right bar button.</p><p>We will build the animation by playing with the frame’s axis (basically translating). This is mostly useful when you have a model presentation and want your UX to stand out!</p><h3>Prerequisites</h3><p>This is an entry-level tutorial. You should be familiar with the frames and bounds of a view. Also, this post follows a programmatic view-building approach, but the animation part will be similar through a storyboard.</p><p>Knowledge of <a href="https://developer.apple.com/documentation/coregraphics/cgaffinetransform">CGAffineTransform</a> and <a href="https://github.com/roberthein/TinyConstraints">TinyConstraints</a> is a plus.</p><h3>Where to Start</h3><p>Our end product will be the animation below. Download the starter project <a href="https://github.com/arjunbaru/mediumArticles">on GitHub</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/314/1*13gWeBw-9fC1b6YMdtZbUA.gif" /></figure><h3>What’s in the Starter Project?</h3><p>Looking through the code, we have a ViewController.swift class that has a table view added with a data source of different cities.</p><p>It doesn’t have a navigation bar yet!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i49LZkiy3f94B4GqgnHltg.png" /></figure><p>Let’s create a CustomNavigationBar<strong> </strong>class<strong>. </strong>Add the CustomNavigationBar.swift<strong> </strong>file to the project.</p><p>First, we will create a custom enum<strong> </strong>(AnimationStyle)<strong> </strong>that<strong> </strong>will guide the view’s animation behavior.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*1Ff0HeGZEcoY96AWX7tPSw.png" /></figure><p>In this tutorial, we will be implementing only left-to-center animation.</p><p>As we are using an enum, we can add other types of animation in the future according to our requirements.</p><p>Let’s create a CustomNavigationBar.swift<strong> </strong>class<strong> </strong>and add the code below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lfXEANwjqa0AasToQFOGlA.png" /></figure><p>We are initializing this class with the animating view and the animation style.</p><h3>Let’s Set Up the UI</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q7r-KkgGns9QPC8bfD18AA.png" /></figure><p>Let’s place the view to the left with a centered-to-Y axis and the height of the superView.</p><p>I am using the TinyConstraint library as a utility to lay out constraints. You can use NSLayoutConstraint as well. Just make sure you place it correctly.</p><h3>Time to Add Magic</h3><p>Add the code below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aAI9cD5rxVw9NrnVXDj7dw.png" /></figure><p>What we are doing here is translating the x-axis with respect to offset the table/scrollView.</p><p>As the origin starts from the top left corner, we will be translating the view and stop once we reach the center of the superView.</p><p>For this, we will take the<strong> </strong>maximum of (zero, ContentOffset) so that -ve translation(of scrollView) can be removed and compare it with the center of the<strong> </strong>superView (whichever is the minimum). Then we will update that as translation.</p><h3>Let’s Connect the Navigation Bar</h3><p>Create the NavigationBar and the view to be animated (in this case, a UILabel) in the ViewController.swift file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dfc9bTdweuZfZWfIKVD_SA.png" /></figure><p>Use ScrollView’s scrollViewDidScroll(_ scrollView: UIScrollView)<em> </em>method and pass the contentOffSet of the tableView:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mFSlaI2ELsF8AwdB9q2q5g.png" /></figure><p>Build and run!</p><h3><strong>Let’s Add and Animate the Navigation Bar Button</strong></h3><p>Add the following code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qmr2rlp_QReUrUXodHJO8Q.png" /><figcaption>Creating an info button with the iOS 13 default image</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*CktFBVTFkC3lpYhCRDg0eg.png" /><figcaption>Placing it in the top right corner</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cnLLW9omLi1t7_94IEfGcw.png" /><figcaption>Increase alpha with an increase in tableView offset</figcaption></figure><h3>Let’s See the Final Result!</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/314/1*13gWeBw-9fC1b6YMdtZbUA.gif" /></figure><p>Awesome! You might be wondering how iOS 13&#39;s large navigation bar does that. Well, that’s a topic for another animation tutorial.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96355c6822ce" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/building-an-animating-navigation-bar-in-ios-13-96355c6822ce">Build an Animating UINavigationBar in Swift</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>