<?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 Christian Schnorr on Medium]]></title>
        <description><![CDATA[Stories by Christian Schnorr on Medium]]></description>
        <link>https://medium.com/@jenoxx?source=rss-6a4fbe4f2473------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Z2_AbOSahyAEc1MEs9A-aw@2x.jpeg</url>
            <title>Stories by Christian Schnorr on Medium</title>
            <link>https://medium.com/@jenoxx?source=rss-6a4fbe4f2473------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 10:38:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jenoxx/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[Minimizing Shared State with Swift Value Types]]></title>
            <link>https://medium.com/@jenoxx/minimizing-shared-state-with-swift-value-types-ae2c39fdfe68?source=rss-6a4fbe4f2473------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae2c39fdfe68</guid>
            <category><![CDATA[value-type]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[reference-type]]></category>
            <category><![CDATA[state]]></category>
            <category><![CDATA[mutability]]></category>
            <dc:creator><![CDATA[Christian Schnorr]]></dc:creator>
            <pubDate>Fri, 11 Oct 2019 16:29:46 GMT</pubDate>
            <atom:updated>2019-10-28T12:39:56.291Z</atom:updated>
            <content:encoded><![CDATA[<p>The Chrono24 iOS app existed back in the Objective-C days and has come a long way since. Back then, we were pretty much forced to inherit from NSObject and therefore use reference types for almost everything. With the introduction of Swift in 2014 and its value types, a whole new world of possibilities opened up.</p><p>In this article we talk about how value types in Swift allow us to write safer code by minimizing shared state, making the code much easier to reason about than before.</p><h3>The Problem with Reference Types</h3><p>Instances of classes have an inherent identity, the <em>object identity</em>: an address on the heap where their data is stored. When passing an object as an argument to some function or assigning it to some variable, we really only copy a pointer to where the object lives on the heap. The object is said to be passed <em>by reference</em>. There is still only one object living on the heap but multiple pointers referencing it.</p><p>In many situations, this is desirable: we only store the potentially expensive object data once and can have as many cheap pointers to it as we’d like. If the object is immutable, i.e. its data doesn’t change over time, this is great.</p><p>But not everything can be immutable. Maybe we need mutability because we cannot configure everything directly in the initializer. Or maybe our use case warrants mutable classes, e.g. a class modeling a conversation that can be marked as read by the user. When we reference instances of mutable classes from different parts of our application, we end up having so-called <em>shared mutable state</em>. That’s potentially dangerous because suddenly one part of the application can mutate the object without the other parts being notified of this change, simply reading the updated data the next time the object is accessed whether they want it or not. In addition to that, every part referencing shared mutable state now has the ability to mutate it even though there is generally some kind of owner managing the data with the other parts merely consuming the data.</p><p>If we don’t actually want to have shared mutable state, we can make defensive copies of our model objects when passing them to another part of the application, such that changes made in one part aren’t visible in the other part. When making defensive copies, a shallow copy is generally not sufficient as the object may itself contain a mutable object. Instead we may need to perform a deep copy, copying the primary object’s contents as well as recursively contained mutable objects. But then again, that would probably be a mutable copy and other parts of the application could mutate it without us knowing if they can somehow get a reference to it. To be really safe, we would need two versions of a data type — a mutable and an immutable version — such that we can pass an immutable copy off to another part of the application.</p><p>When different parts of the application intentionally share mutable state, we need to make sure that when one part modifies the shared state, the other parts get a chance to react accordingly. We can do this by implementing the observer pattern for our mutable classes. To correctly implement the observer pattern, a mutable object must observe all of its referenced objects to notify its own observers if one of the referenced objects changed. And if one of its references changes to point to a new instance, it must not forget to unsubscribe from the old instance and subscribe to the new instance.</p><p>Unfortunately immutable types can very quickly turn into mutable types due to new requirements, and then we have a real problem: Up until now we correctly assumed the type to be immutable in code, not making defensive copies or registering as an observer where we would otherwise have for a mutable data type. All these parts need to be updated to account for the class no longer being immutable. It may not be easy to find all the affected parts of the code. We must also consider objects that appear to be immutable at first glance, but contain immutable references to mutable objects: once a deeply nested type becomes mutable, so do all of the types recursively referencing it. And then there also is the possibility of someone slipping us a mutable subclass of an immutable superclass without us knowing…</p><h3>How Value Types Save the Day</h3><p>Value types don’t have an inherent identity as reference types do. All they have is content, and if that content is equal to the content of another value then they are considered equivalent and substitutable. Value types are passed <em>by value</em>: when passed along to another part of the program, their content is copied, not just the address of the source value. As a result, instances of value types are not shared — everyone automatically gets his own defensive copy and can mutate it freely without affecting the rest of the application. This allows us to write more predictable code that is easier to reason about. Of course value types live somewhere in memory too and therefore have an address, but we generally don’t see or deal with this address.</p><p>The mutability of a value type is not baked into the type itself. Instead, the declaration site gets to choose whether the instance should be immutable (using let) or mutable (using var). If declared as immutable, neither the value itself nor nested values can be reassigned or have mutating methods invoked, even if the nested values are defined as mutable within their container — after all, the whole thing is declared to be constant. If declared as mutable on the other hand, all of the above operations are permitted. Note that there is no difference between mutating an existing value or assigning an equivalent new value since value types don’t have an inherent identity as reference types do. With just one implementation of the type, we get both an immutable and a mutable variant, with the mutable parts simply being unavailable when used as an immutable type.</p><p>Also note that this is by no means exclusive to Swift. In fact, it can be done in plain C with just structs and const. Swift does add a couple of niceties such as support for methods and reference counting for nested reference types though.</p><h3>Value Types and Identities</h3><p>Identities are crucial to distinguishing things from one another, and classes give us the object identity for free. Let’s imagine we have a list of watches and each watch is being represented by a cell in a UITableView. We can use the list of watches to feed the table view, and when a new list of watches is set, we can tell where cells need to be inserted, deleted, or moved based on the watch identities.</p><p>Except object identity isn’t what we want here: When we get an updated set of watches from an API endpoint and want to present those to the user, after deserialization we have objects with all new identities. Our update logic based on object identities would then simply remove all of the old cells and create new cells for all of the watches.</p><p>So what kind of identity do we want here? In the example above, the objects after the update still represent the same thing: the same underlying records in our database. In a database we generally have a primary key that defines the identity of the records we are dealing with; something like a watchID for the example above. This key alone defines the <em>record identity</em> of a watch. And we can have multiple <em>snapshots</em> of the same record at different points in time (say before and after an update) and associate them using their record identity.</p><p>Of course this is possible with reference types, too. But value types make this really easy because we can ensure that the snapshots are immutable and because they don’t bring this other kind of identity with them, that — in our use case — has no meaning whatsoever.</p><p>SwiftUI introduced the <a href="https://developer.apple.com/documentation/swift/identifiable">Identifiable</a> protocol to allow types to vend their record identity and several UI components that build upon the concept of record identity. Soon after its introduction the protocol was moved to the standard library for everyone to use.</p><p>protocol Identifiable {<br> associatedtype ID: Hashable<br> var id: ID { get }<br>}</p><h3>Observing Changes</h3><p>Implementing the observer pattern for (nested) mutable classes is very error-prone, and even if implemented correctly there are a couple of drawbacks: Firstly, mutations are communicated in a very fine-grained fashion. Multiple consecutive mutations notify the observer for each mutation individually, even though we are much rather interested in the change as a whole. And secondly, because we generally don’t know what part of the object changed, we need to assume the worst and update everything that depends on any part of the object.</p><p>For value types, on the other hand, we don’t need to implement observation of this kind. Recall that for value types, the declaration site defines the mutability of a value. Immutable values simply aren’t allowed to change and mutable values can only change as a whole, i.e. mutations to the value itself or one of its nested values result in a mutation of the entire value, causing a potential didSet property observer to be called. This way we can perform mutations of arbitrary scale or even assign an entirely new value and have the property observer be called just once, plus we have access to the oldValue to find out what part of the data actually changed and perform our resulting updates more efficiently.</p><h3>Value Semantics</h3><p>Not everything can be a value type. Sometimes we need the unique identity the address of a value gives us. Sometimes the size of a type changes dynamically, requiring reallocation, such as arrays that have elements removed or inserted. And value types can even behave like reference types, for example if they reference shared mutable storage such as global variables or if they contain mutable objects.</p><p>What really matters is what kind of <em>semantics</em> a type has; what guarantees it makes, how it behaves. In the standard library, even collections have value semantics: an array, a dictionary, or a set is just a pointer to (potentially shared) mutable storage on the heap, but these types implement an efficient copy-on-write mechanism that copies the underlying storage prior to mutation if it is referenced more than once.</p><h3>Observation and Diffing in SwiftUI</h3><p>In SwiftUI, the body of a view is invalidated when the value of a Binding or ObservableObject that is read in the body changes. On the next run loop, the view bodies are then being re-rendered and the resulting virtual view tree is diffed to find out what changes need to be applied to the view hierarchy. This is implemented as an invalidation instead of a direct reload such that multiple consecutive updates can be grouped together, something the observer pattern as implemented by ObservableObject does not allow for.</p><p>The content of dynamic lists is diffed according to the record identity of the Identifiable model values to find out where cells need to be inserted, deleted, or moved.</p><h3>Value Types at Chrono24</h3><p>While we do not currently use SwiftUI, there are a couple of lessons to be learned by how things work there, namely data flow and how updates are performed.</p><p>In the Chrono24 iOS application, we generally want to avoid shared mutable state. We therefore use value types for most of our data. Our data generally has an owner, either a service or a controller, who manages it and passes snapshots of the data to other components that need it, primarily views. The views can therefore not mutate the data directly and must instead send actions back to the controller to request changes. The controller can then handle the action, possibly mutate the data as a result, and write (a snapshot of) the updated data back to the view and all other parts that require the updated data.</p><p>Building on top of that, we implement the Identifiable and Equatable protocols in our model values all throughout the app in order to allow for efficient updates of the view hierarchy once the underlying data changes: Just by extracting the primary keys of our models and comparing them to those before the update, we can tell where items need to be inserted, deleted, or moved. For snapshots of records whose identity is present in both the old and the new data, we can then check if there have been changes to the rest of the record using its Equatable conformance. If there are, we pass the new snapshot to the respective view so that it can redraw; if there aren’t, then the two snapshots are in fact substitutable and we don’t need to do any extra work.</p><p>You can find a sample project showing the problems with reference types and how we use value types at Chrono24 to solve common tasks when developing an iOS app on <a href="https://github.com/Chrono24/Swift-Value-Types">GitHub</a>.</p><p>In conclusion, these are our biggest takeaways:</p><ul><li>By using value types for our model types we can reduce shared mutable state and observation bookkeeping logic.</li><li>When using value types for your models, think of them as snapshots of a record at different points in time and define their record identity in terms of the primary key in the underlying database.</li><li>Value types allow us to perform UI updates more efficiently: we can trivially compose multiple updates together and perform only a single efficient redraw because we know both the old and the new value and can find out which parts do (or don’t) need to be redrawn.</li></ul><p><em>This article was originally published on the </em><a href="https://www.chrono24.net/minimizing-shared-state-with-swift-value-types/"><em>Chrono24 Blog</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae2c39fdfe68" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Gestures in Fluid Interfaces - On Intent and Projection]]></title>
            <link>https://medium.com/ios-os-x-development/gestures-in-fluid-interfaces-on-intent-and-projection-36d158db7395?source=rss-6a4fbe4f2473------2</link>
            <guid isPermaLink="false">https://medium.com/p/36d158db7395</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[user-interface]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[design]]></category>
            <dc:creator><![CDATA[Christian Schnorr]]></dc:creator>
            <pubDate>Mon, 09 Jul 2018 18:51:10 GMT</pubDate>
            <atom:updated>2018-07-09T18:51:10.729Z</atom:updated>
            <content:encoded><![CDATA[<h3>Gestures in Fluid Interfaces — On Intent and Projection</h3><p>In my last article we discussed how to craft spring animations between two endpoints that feel natural. When finishing an interactive transition, this includes picking an initial velocity that matches the one of the gesture. But that’s only half the battle — just as important is finishing the transition the way the user intended to, i.e. choosing the right endpoint for the animation.</p><p>Inspired by the 2018 WWDC session <a href="https://developer.apple.com/videos/play/wwdc2018/803/">“Designing Fluid Interfaces”</a>, we’ll discuss a fairly simple approach to aligning an animation’s endpoint with the user’s intent.</p><h3>Intent on the Home Screen</h3><p>Let us take a close look at a gesture we use every day: changing between pages on the home screen. You might just give it a quick flick and expect to be taken to the next page. But when implementing such a gesture, how could we possibly know what the user intended to do?</p><p>If we were to take only the current scroll position into account and animate to whatever page is closest when the user releases his finger, one would be forced to swipe at least halfway over. On larger screens like on the iPad it becomes obvious that this is rather unwieldy.</p><p>Obviously we need more information than just the current scroll position in order to pick the right endpoint; more information about how we got there, so that we can make a reasonable assumption on how the user would have continued the motion. A natural thing to look at is the momentum of the gesture, and that’s something UIPanGestureRecognizer already gives us out of the box. Note that it should probably to be a combination of position and velocity: The closer one’s finger is to the halfway point when lifted off the screen, the less velocity should be required to move content past that point. But just how much velocity is required to cover the remaining ground?</p><h3>Projection</h3><p>Turns out we already have a very good intuition for that. We move content around the screen every day, most prominently perhaps content embedded in UIScrollViews. Everybody has a feeling for how fast one needs to flick across the screen to scroll a certain distance, and this application is no different: It’s very reasonable to push content such that it would come to rest at (or close to) the position where we want it to be.</p><p>When a standard scroll view decelerates, the velocity with which it moves decreases exponentially over time. The default deceleration rate is λ = 0.998, meaning that the scroll view loses 0.2% of its velocity per millisecond. For any point in time we can compute the remaining velocity as v(t) = v_0·λ^(-1000t), where v_0 is the initial velocity at t = 0.</p><p>The distance traveled is the area under the curve in a velocity-time-graph, thus the distance traveled until the content comes to rest is the integral of the velocity from zero to infinity. Luckily this integral converges and we find s(t) = -0.001 · v_0 / log(λ). In the WWDC session <a href="https://developer.apple.com/videos/play/wwdc2018/803/">“Designing Fluid Interfaces”</a>, Apple refers to the process of finding the position at which some object comes to rest as <em>projection</em>. They provided a different formula to calculate it though!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/443b7fc31c117875843d2a6d91699d88/href">https://medium.com/media/443b7fc31c117875843d2a6d91699d88/href</a></iframe><p>This one I can’t explain to you where it comes from. I only know that Facebook Pop <a href="https://github.com/facebook/pop/blob/92b2c5b7bcad64f7507da34f921492c71ff1d330/pop/POPDecayAnimationInternal.h#L34">uses this equation as well</a>. But Pop, too, assumes an exponentially decaying velocity — and these equations for position and velocity simply don’t fit together. Differentiating Pop’s equation for the distance traveled with respect to time, which would explain the projection formula above, doesn’t even yield the specified initial velocity for t = 0.</p><p>For common deceleration rates the two equations for projection <a href="https://www.wolframalpha.com/input/?i=plot+1%2F1000*lambda%2F(1-lambda)+and+-1%2F(1000log(lambda))+from+0.8+to+1">differ by less than a percent</a> though, so I’d suggest using the one you can reason about:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0a781a96f3e1555d1bbf5e981c0de8c0/href">https://medium.com/media/0a781a96f3e1555d1bbf5e981c0de8c0/href</a></iframe><p>Note that the concept of projection is not limited to translational velocities in any way. It could also be applied to, say, the angular velocity of a rotation gesture.</p><h3>Choosing the Right Endpoint</h3><p>Now that we have projection all figured out, let’s turn our attention back towards choosing the endpoint that matches the user’s intent. For one-dimensional interactions like paging on the home screen and open/closed-drawers like notification center, the process is fairly trivial: calculate the projected position and pick whatever endpoint is closest to that position.</p><p>Taking it to more dimensions is where things get a little tricky. We’ll discuss a two-dimensional interaction here, and that’s already difficult enough. So difficult in fact, that no one seems to really have it figured out: The system PIP on the Mac is horrendous — it doesn’t respect the momentum at all. On the iPad it does, but flicking the PIP still feels very clunky. Better implementations include the overlay in FaceTime and Twitch on iOS, but even they don’t quite feel right.</p><p>A naïve approach would be treating each dimension of the gesture separately, in this case the horizontal and vertical position. That’s what FaceTime and Twitch appear to be doing, but there’s a problem with that: Just like we are used to giving content a quick flick when trying to scroll to the very top or bottom of a list, we may do the same to move the overlay to the top or bottom edge. However, our gestures aren’t 100% accurate and almost always include some momentum in a secondary, unintended dimension. The problem with this is that very little directed momentum is enough to move past the halfway point along a given axis, and the unintended momentum in a secondary dimension is often enough. Therefore when treating each dimension separately, the overlay often swaps sides contrary to the user’s intent.</p><p>A potential solution I’ve come up with is instead treating the gesture as a whole: It has momentum along a primary axis, and if the momentum along the other axis is much smaller it was probably unintended and should not have the same weight when determining the endpoint of the gesture:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/85a1ffc39748eeb157ed2f4f087225fe/href">https://medium.com/media/85a1ffc39748eeb157ed2f4f087225fe/href</a></iframe><h3>Additional Resources</h3><p>I replicated the FaceTime overlay discussed in the aforementioned <a href="https://developer.apple.com/videos/play/wwdc2018/803/">WWDC session</a> in a <a href="https://github.com/jenox/UIKit-Playground/tree/master/02-Gestures-In-Fluid-Interfaces/">demo project</a> on GitHub. It’s a great session, you should really check it out. I also encourage you to play around with the endpoint computation and assure yourself that the naïve approach of treating each dimension separately doesn’t quite feel right. If you have any other suggestions for computing the intended endpoint in a two-dimensional context, I’d love to hear about it!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36d158db7395" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ios-os-x-development/gestures-in-fluid-interfaces-on-intent-and-projection-36d158db7395">Gestures in Fluid Interfaces - On Intent and Projection</a> was originally published in <a href="https://medium.com/ios-os-x-development">iOS App Development</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Demystifying UIKit Spring Animations]]></title>
            <link>https://medium.com/ios-os-x-development/demystifying-uikit-spring-animations-2bb868446773?source=rss-6a4fbe4f2473------2</link>
            <guid isPermaLink="false">https://medium.com/p/2bb868446773</guid>
            <category><![CDATA[physics]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[animation]]></category>
            <dc:creator><![CDATA[Christian Schnorr]]></dc:creator>
            <pubDate>Sat, 30 Jun 2018 23:06:56 GMT</pubDate>
            <atom:updated>2018-07-07T07:33:04.388Z</atom:updated>
            <content:encoded><![CDATA[<p>Spring animations first became part of the public API back in iOS 7, but the damping-duration-interface from back then was very unnatural. It is still around today and we’ll discuss why it is problematic in a bit. Things got a lot better with the addition of UISpringTimingParameters and UIViewPropertyAnimator in iOS 10, but it is still harder to craft animations that feel natural than it should be.</p><p>So what are spring animations, how do they work, and how can we craft animations that feel just right?</p><h3>The Physics Behind Spring Animations</h3><p>Back in physics class in high school, we studied simple harmonic motions using the example of a mass on a spring. One can manually displace the mass from its equilibrium position, and the force exerted by the spring pulls the mass back towards equilibrium. In high school we studied this as an undamped system, i.e. one without friction, resulting in a sinusoidal motion of the form s(t) = s_0·cos(ωt).</p><p>But chances are, when using a spring to drive an animation, that you want the animation to draw to a close sooner or later. This can be achieved by gradually withdrawing energy from the system as a result of damping. Viscous damping is a common form of damping where the damping force’s magnitude is proportional to the velocity s′(t), but is exerted in the opposite direction. By applying Newton’s second law, balance of forces, we get the second-order differential equation ks(t) + cs′(t) + ms″(t) ≡ 0 with mass m &gt; 0, stiffness k &gt; 0, and viscous damping coefficient c ≥ 0, which s(t) must satisfy. For arbitrary initial displacement s(t = 0) = s_0 and velocity s′(t = 0) = v_0, the differential equation has a unique solution whose form depends on the concrete values of the spring parameters:</p><ul><li>For c &lt; 2sqrt(km) we have an underdamped system. The system oscillates about its equilibrium position in a decaying sinusoidal motion, regardless of the initial velocity. The oscillation is what makes it feel “springy”.</li><li>For c &gt; 2sqrt(km) the system is overdamped. Here the damping force is strong enough to prevent the system from oscillating. With sufficiently large initial velocity the target value can be overshot though.</li><li>For c = 2sqrt(km) the system is critically damped. This is where the damping force is just strong enough to prevent oscillation. Critically damped systems converge towards equilibrium the fastest of all three cases.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/495/1*Y8U7t6mhv_vKl8z4bshYzA@2x.png" /><figcaption>The equations of motion for an underdamped (red), critically damped (green), and overdamped (blue) spring.</figcaption></figure><p>At the time of writing overdamped springs are not supported by UIKit. Besides, I don’t know where you’d ever want to use an overdamped spring animation — if you need something bouncy, you’d go with an underdamped spring; if you don’t want it to bounce, you’d typically want the animation to settle as quickly as possible and use a critically damped spring.</p><p>For more information on the concrete forms of s(t), please refer to the following <a href="https://github.com/jenox/UIKit-Playground/tree/master/01-Demystifying-UIKit-Spring-Animations/Resources/DampedHarmonicSpring.gcx">Grapher file</a>.</p><h3>Designing Spring Animations</h3><p>With a trained eye you can see that with parameters αm, αk and αc, the differential equation from above has the same solution s(t) for any α &gt; 0. This means that a spring’s characteristics are uniquely determined by just two parameters: We could assume a unit mass and tweak only the spring’s stiffness and its damping coefficient.</p><p>But I highly doubt that anyone can make sense of concrete values for these parameters without plotting the corresponding equation of motion. In the 2018 WWDC Session <a href="https://developer.apple.com/videos/play/wwdc2018/803/">Designing Fluid Interfaces</a>, Apple suggested using a different set of parameters that are much more design-friendly: damping ratio and frequency response. The damping ratio is the ratio of the actual damping coefficient to the critical damping coefficient. A damping ratio of 0 therefore describes an undamped system, while a damping ratio of 1 describes a critically damped system. The frequency response is defined as the duration of one period in the undamped system. This property essentially determines how fast the animation will feel, but it should not be confused with the duration of the entire animation: In theory spring animations never really come to a rest — they are simply assumed to have ended when the amplitude becomes small enough.</p><p>Unfortunately, UIKit does not currently allow us to construct a spring animation using these parameters. While we can create spring timing parameters using some damping ratio, we cannot specify the frequency response. In fact, there is an infinite number of springs with a given damping ratio that all behave differently! The spring’s underlying physical properties are only determined when we create a UIViewPropertyAnimator with a fixed duration, but that duration is the duration of the entire animation, the duration until a small enough amplitude is reached — a value not very meaningful for design work either. The whole point of using spring animations is having an animation that feels natural, with the spring parameters you choose — not a spring animation that is, say, critically damped and whose displacement from equilibrium becomes negligible (whatever that may mean…) after precisely 0.75 seconds. The latter will likely feel a little off.</p><p>If you instead create spring timing parameters with a mass, damping coefficient and stiffness, the duration you pass to a UIViewPropertyAnimator is ignored, as it should, because the three parameters alone uniquely identify the spring’s equation of movement, and the animation should run until the amplitude becomes negligible.</p><p>So if you want to craft a spring animation that feels natural, don’t explicitly specify the animation’s duration. Instead, create timing parameters that completely specify the spring’s underlying parameters and let the animator derive its duration from those parameters. The following snippet shows how to convert damping coefficient and frequency response to mass, stiffness, and viscous damping coefficient:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/08d730373ed94f91e1880957b0563aba/href">https://medium.com/media/08d730373ed94f91e1880957b0563aba/href</a></iframe><h3>Springs in an Animation Context</h3><p>Animations interpolate between their from- and to-values using a so-called timing function f(t) according to the equation value(t) = start + f(t)·(end — start). This is done regardless of how big or small the distance between the from- and to-value is. For a linear animation the timing function would have the form f(t) = t / duration, for example. But we can use just about any f(t), including one motivated by the motion of a spring, as long as f(0) = 0 and f(duration) = 1, i.e. the animations starts at the from-value and somehow transitions to the to-value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/495/1*N5sixfsV0vOsSGG8WnJe6g@2x.png" /><figcaption>An underdamped spring timing function (red) and a linear timing function (green).</figcaption></figure><p>This hints at the key difference between physical springs and animations already: the equation of motion for a spring deals with absolute units, say meters. Timing functions, on the other hand, are normalized to the unit interval with their codomain being unitless, indicating the fraction of the animation that has completed. The spring’s velocity is still the derivative of its displacement, but in an animation context this, too, becomes a relative quantity: the fraction of the animation that is completed per second. Therefore a relative initial velocity of 1 corresponds to an absolute initial velocity that covers the entire animation distance in one second. Note that evaluating the normalized spring timing function and using its value to interpolate the from- and to-value yields the same result as evaluating the spring’s equation of motion with appropriately scaled initial position and velocity.</p><p>When determining the initial velocity of a normalized spring timing function, think of it as some sort of inverse linear interpolation: With what fractions do you want the from- and to-value to be interpolated? This obviously depends on the desired absolute initial velocity of the animation. Let’s say you use a pan gesture recognizer to let the user move some object and want to start a spring animation to the object’s destination when the user lifts his finger, using the touch’s velocity as the initial velocity for the spring animation. We know that the current position corresponds to a fraction complete of 0 and the target position to a fraction complete of 1, thus we can calculate the relative initial velocity as v_rel = v_abs / (target — current).</p><p>You may wonder what happens if we are already at the target value. We’d divide by zero, resulting in an infinite relative initial velocity, regardless of the absolute initial velocity! The problem is that when the from- and to-value are identical, any inter- or extrapolated value will be, too, and we can’t possibly compute a reasonable relative initial velocity for the spring. In order to preserve the absolute initial velocity, we must first displace the from-value a tiny bit so that we can map the values to the unit interval bijectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/495/1*Y8jKgiIuQEGHYr4ZL4K1qw@2x.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/495/1*e-Cq1ACOppRUvAYLRtN2uA@2x.png" /><figcaption>Left: The motion of a critically damped spring with some initial velocity and no initial displacement from equilibrium. Right: A corresponding spring timing function for when the from-value is manually displaced by -0.5.</figcaption></figure><p>The smaller we make the manual adjustment, the less noticeable it becomes, and the better the timing function matches the motion of a spring with non-zero initial velocity and no initial displacement from equilibrium. For very small manual adjustments we get relative displacements and velocities of surprisingly high magnitude. Keep in mind though that these values must be interpreted relative to the distance between the animation’s endpoints, which we chose to be very small. In the figure above, the timing function peaks at a relative displacement from equilbrium of roughly 15 which translates to an absolute displacement of 7.5, as we chose the distance between from- and to-value to be 0.5. This matches the motion of the spring which peaks at 7.5, too.</p><h3>Initial Velocity as a Vector</h3><p>The initial velocity of a spring is a scalar value, not a vector. However, UISpringTimingParameters makes us to specify the initial velocity as a vector. What is going on here?</p><p>The reason we get to specify a vector is to make it easier to animate two-dimensional properties like a view’s position, where the initial velocity might be different along the x and y axes. This really just creates two spring animations under the hood, one for the x position and one for the y position, with potentially different initial velocities and a shared completion handler.</p><p>When animating one-dimensional properties, the y component of the initial velocity is completely ignored. The documentation states that for 1D-properties, the vector’s magnitude is used as the animation’s initial velocity. This is plain wrong. Besides, this would prevent us from having negative initial velocities.</p><p>I have found a view’s position (center) to be the only property where an initial y velocity has an effect. When animating a view’s size, UIKit does not distinguish between width and height and uses the x component for both. This is also the case when animating a view’s transform, even if it is only a translation.</p><h3>Additional Resources</h3><p>I wrote a little demo app that lets you play around with spring parameters and animations driven by those. The sample code also shows how to properly calculate the relative initial velocity, including the aforementioned displacement that is necessary when already at the target value. You can find said project <a href="https://github.com/jenox/UIKit-Playground/tree/master/01-Demystifying-UIKit-Spring-Animations/">on GitHub</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2bb868446773" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ios-os-x-development/demystifying-uikit-spring-animations-2bb868446773">Demystifying UIKit Spring Animations</a> was originally published in <a href="https://medium.com/ios-os-x-development">iOS App Development</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>