banner



How To Animate The Transition Between Views Swift

    Working with iOS View Animations and Transitions in Swift

    If you utilise an Apple tree device, you lot've probably seen a agglomeration of animations from third-party apps or Apple'southward stock apps. If y'all e'er wished yous knew how to do that, merely idea information technology looked too complicated, your wish is nigh to come truthful. Follow along with me and you'll discover that creating animations in iOS is non only uncomplicated, merely as well fun.

    Animations grab a user'due south attending and let them to focus on what'south important on the screen. Animations also highlight changes on the screen and can aid a user learn to navigate your app. But who are nosotros kidding, everyone loves animations. They're just and then cool.

    Tools You'll Need

    To follow along with this tutorial, assuming you are an iOS developer looking to explore the world of animations, yous volition demand a couple of prerequisites:

    • A Mac running the latest bespeak release of macOS X Sierra or later.
    • Xcode 8 or later.
    • Basic noesis of the Swift 4 linguistic communication and Car Layout.

    If yous don't have any of these things, you lot tin go alee and get them, I'll be hither...

    Getting Started

    Now that you lot have what you'll need, I have already set a minor project for y'all to work on. You can download information technology here or if you adopt to check out the Git repo, you lot tin can exercise that likewise.

    In one case yous've downloaded or cloned it, go ahead and open the project file. You should find a file structure that looks similar this:

    Open up Main.storyboard . In information technology you'll see a black and gold-themed view controller.

    It's aptly named Next Level Designs and contains a label, ii UIViews: i aureate, the other light-green, and a Transition button at the bottom. The gilded UIView is layered on top of the greenish ane; that'south why you can't see information technology at the moment.

    You can go ahead and run the project to run across how the design looks in action. We will be using this view controller to demonstrate view transitions.

    Let'south become started.

    View Transitions

    As you might have guessed, we will be transitioning the UIViews. Our goal is simple: when we click the Transition push button, we want a transition to happen from the gilded UIView to the light-green 1 and vice versa when we click it again.

    But before we can do that, we have to connect some outlets to a custom grade. Open up Main.storyboard , select the Next Level View Controller, and click on the Assistant Editor in the acme right section of Xcode (the one that looks like 2 overlapping circles).

    The kickoff thing nosotros desire to connect is our two UIViews, and since 1 is overlayed on top of the other, the easiest way to connect them would exist from the Document Outline on the left.

    From at that place you can either Selection + drag or correct-click drag to the Swift file but above the viewDidLoad() method.

    Proper noun the aureate i goldenView and hit connect.

    Yous can ostend which UIView yous are connecting by checking its groundwork color in the Attributes inspector on the right side.

    Do the same for the greenView and finally connect the Transition push afterwards the viewDidLoad() method.

    Make sure it is an Action and is of blazon UIButton.

    Now that that'due south done, become set to request the help of our resident transition API from the good folks at Apple tree.

    The Transition API

    If yous're familiar with the UIKit Animations API, the Transition API is quite similar to that and fairly simple to implement. All the same, at that place are a few differences and nosotros are going to cover all of them.

    The get-go affair to know is that the Transition API has two implementations, which on the surface level are very similar because they do the same thing. However, they operate a little differently.

    In our transition() action method, if y'all start to type UIView.transition, the XCode autocomplete will give you a couple of options:

    We are interested in the first ii options and to best explain how they work, we are going to use them both to transition our UIViews.

    UIView.transition(with: ...)

    Permit's start with the second option; the one with the with: parameter. Information technology'southward the more straightforward one.

    View transitions are predefined, which means they're somewhat limited, simply very powerful and uncomplicated to implement. To implement the transition, you take to do one unproblematic thing: pair a transition trigger with a predefined transition.

    Naturally your next questions are, "That's great, but what is a transition trigger? What are these predefined transitions? And how practice I exercise whatever of that?"

    Have patience, all volition be revealed in due time. Let's beginning with transition triggers.

    At that place are 3 triggers that should cause a view to transition:

    • isHidden - this one triggers a view'southward isHidden property and causes information technology to disappear from view.
    • addSubview() - this method adds a subview to a view's view hierarchy.
    • removeFromSuperview() - this does the opposite and removes a view from its superview's view hierarchy.

    The triggers become in the animations: closure.

    As for the transitions, there are seven:

    • .transitionFlipFromLeft
    • .transitionFlipFromRight
    • .transitionFlipFromTop
    • .transitionFlipFromBottom
    • .transitionCurlUp
    • .transitionCurlDown
    • .transitionCrossDissolve

    The transitions actually do what they say and nosotros'll meet this in a while. They go in the options: parameter.

    Now that yous're up to speed, let's get transitioning. In your UIView.transition(with: ...) implementation, accept the with: parameter be the goldenView because it's the one on top, have a duration: of 0.5, in the options: set, input [.transitionFlipFromRight] , and in the animations: closure, set goldenView 'south isHidden property to true.

    Your implementation should look like this:

                      UIView.transition(with: goldenView,                          duration: 0.5,                          options: [.transitionFlipFromRight],                          animations: {                                                        self.goldenView.isHidden = truthful        },                          completion: nil)                                  

    Build and run the project, hit the Transition button, and see what happens.

    Congratulations on your first view transition. Give yourself a self-v!

    Our transition project is far from consummate though. The transition just happens one time and that's non the effect we are going for. We demand to detect a mode to make it transition back and forth.

    In the same file, correct under the outlets for our UIViews, define a private constant, call it isFlipped , and initialize information technology to faux.

                      private var isFlipped: Bool = imitation                                  

    Adjacent, tell our transition method which UIView it has to flip when the button is clicked.

    The carte du jour we need to flip will be goldenView when isFlipped is true and greenView when isFlipped is imitation.

    In our button action method, add a ternary operator based on our isFlipped belongings that determines whether the card to flip will be the goldenView or the greenView .

                      @IBAction func transition(_ sender: UIButton) {        isFlipped = !isFlipped                                  

    However, our isFlipped property, at the moment, is static, which means it will always be false. So we need to change the value of isFlipped everytime the button is clicked.

    To practice that, add the post-obit only to a higher place the declaration of cardToFlip:

    One last thing, in the UIView.transition(with: ...) method, supervene upon any case on goldenView with cardToFlip.

    The whole method should at present await like this:

                      @IBAction func transition(_ sender: UIButton) {        isFlipped = !isFlipped         permit cardToFlip = isFlipped ? goldenView : greenView         UIView.transition(with: cardToFlip!,                          duration: 0.five,                          options: [.transitionFlipFromRight],                          animations: {                                                        cardToFlip!.isHidden = truthful        },                          completion: nil)    }                                  

    Build and run the projection. Notice at present that the cards transition interchangeably.

    Oh, what'south that? The cards flip correctly and so disappear? Of course they do! That'south considering nosotros told the cardToFlip to be subconscious and didn't tell it to come up out of hiding.

    To gear up it, we have to use the completion closure and trigger the isHidden belongings of the cardToFlip back to false. Your completion closure should now look like this:

                      completion: { _ in              cardToFlip?.isHidden = false        })                                  

    Build and run the project 1 more than time.

    You should take run across another problem and this fourth dimension, the goldenView transitions out of view and then awkwardly reappears after a while. I know what you lot're probably thinking and no, I'grand not messing with you. This is actually a teachable moment virtually the view bureaucracy.

    I'g non going to get deep into the view bureaucracy considering that'due south non what this article is about. But basically, views tin can also human action as containers for other views and they thus create a view bureaucracy.

    In our specific example, our ii UIViews are independent in the main view of the view controller, the root view, and are therefore its subviews. The goldenView is initially placed in front of the greenView and volition remain there unless the order is changed.

    Luckily for united states of america, there is a congenital-in method that can help us out.

    First, we have to capture our bottomCard. Then, beneath our ternary operator for the cardToFlip, add another for the bottomCard.

                      let bottomCard = isFlipped ? greenView : goldenView                                  

    Adjacent, in the completion closure only above where we tell our cardToFlip to cease being hidden, add the following line of code to bring the bottomCard to the front:

                      self.view.bringSubview(toFront: bottomCard!)                                  

    Your whole action method should now await like this:

                      @IBAction func transition(_ sender: UIButton) {        isFlipped = !isFlipped         let cardToFlip = isFlipped ? goldenView : greenView        let bottomCard = isFlipped ? greenView : goldenView         UIView.transition(with: cardToFlip!,                          elapsing: 0.five,                          options: [.transitionFlipFromRight],                          animations: {                                                        cardToFlip?.isHidden =  true        },                          completion: { _ in                             self.view.bringSubview(toFront: bottomCard!)                            cardToFlip?.isHidden = false        })    }                                  

    At present build and run the projection again. I promise it volition piece of work this time. 😄

    Look at that! That's the exact effect we were going for.

    Ane more matter: when a transition is triggered by adding or removing views from the hierarchy, i.eastward ., addSubview() and removeFromSuperview() , y'all need to use the view's superview in the with: parameter.

    When a transition is triggered by isHidden, the view acts as its own container view.

    At present permit's await at the other variation of the transition API.

    UIView.transition(from: ...)

    This variation, on the surface, seems like the simpler one to utilise. However, there are some underlying functionalities that happen, as yous'll discover out in a bit.

    We are going to apply the exact same transition to our UIViews as we did before, so get ahead and annotate out the previous UIView.transition(with: ...) implementation.

    Just like earlier, in our button's action method, right nether the definition of bottomCard, start typing UIView.transition, and from the Xcode autocomplete, pick the offset variation--the one with the from: parameter.

    Nosotros would like to transition from the cardToFlip to bottomCard. So we are going to have cardToFlip for the from: parameter and bottomCard for the to: parameter. Permit's have the same 0.v seconds for the duration: parameter and let's use a [.transitionCurlUp] for the options: parameter. Have the completion: be cipher for now.

    Your transition method should expect like this at present:

                      UIView.transition(from: cardToFlip!,                          to: bottomCard!,                          elapsing: 0.5,                          options: [.transitionCurlUp],                          completion: nil)                                  

    Build and run the projection.

    The first transition happens equally expected, just when you click the button the second time, the compiler hits you with a ⚠ fatal mistake.

    You may take noticed that this variation doesn't have an animations: closure like the other, and we need the animations: closure to trigger the transition. Well, equally I mentioned earlier, this variation has some automated processes happening under the hood.

    If you check your variables view at the bottom, you will detect that the bottomCard, which in this example is the goldenView , is cypher.

    Here'southward what happened: the automated transition trigger removed the goldenView from the view hierarchy.

    In the official Apple documentation, they state that, in this variation, the fromView: is removed from its superview equally part of the transition.

    Well, that's all fine, but nosotros can't just live with this fatal error. We accept to fix it somehow and at that place are ii ways to go about that.

    One would be to add the cardToFlip back to its superview's view bureaucracy in the completion: closure and bring the bottomCard to the front end as we did previously. But y'all've already learned how to do that, so let's explore the other, swifter (pun intended 😏) option.

    In the options: parameter set, add another pick named .showHideTransitionViews . What this does is simply hide the fromView instead of removing it from the view hierarchy.

    Your transition method should now look like this:

                      UIView.transition(from: cardToFlip!,                          to: bottomCard!,                          duration: 0.5,                          options: [.transitionCurlUp, .showHideTransitionViews],                          completion: cipher)                                  

    Build and run the project ane more time.

    Our transition now works well, however, in that location's one small problem. The whole page, instead of the view, curls up, and we definitely don't want that. In this variation of the transition method, the transition merely happens on the superview, and unfortunately, there's no way to make the transition happen specifically on the subview. And that's the limitation that comes with automation.

    The only piece of work-around would be to embed our 2 UIViews in another UIView of the aforementioned size and position that will act as their superview instead of the main root view.

    To do this, open Main.storyboard and in the document outline, highlight both UIViews past Command + clicking both of them. And so go to Editor/Embed In/View.

    Yous should now see a white view that'due south slightly larger than the other two. And yous should notice in the document outline on the left that our two UIViews are at present subviews of the new UIView.

    Resizing the new UIView might evidence tricky, so I'm going to walk you through it.

    • First, take hold of the left edge of the white UIView and bring it inside the bounds of the main root view.
    • Next, select both the goldenView and the greenView and move them simultaneously toward the top left corner of the white UIView and marshal them perfectly with the white UIView'south summit and left edges.
    • Now, take hold of the bottom right corner of the white UIView and resize it to fit the dimensions of the goldenView and the greenView .
    • Finally, select the white UIView from the document outline and simultaneously move all three UIViews to where the goldenView and the greenView previously were.

    Build and run the project for the final time and spotter the dazzler of your work.

    As always, it's up to y'all at present to play around and explore the other transition options and run into which one y'all similar all-time.

    You lot can download the complete tutorial project here or check out the repo on GitHub and compare with your ain.

Source: https://www.twilio.com/blog/ios-view-animations-transitions-swift

Posted by: lewisovelly1950.blogspot.com

0 Response to "How To Animate The Transition Between Views Swift"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel