Swift Gesture Recognizer Tutorial - Pan

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey guys welcome back for another video my series on iOS interview questions today were going to be talking about UI gesture recognizers now I got asked to work with these about three or four times throughout my interview process whether that was part of the coding exercise in a phone screen or part of the actual on-site technical interviews so if you're interviewing around for jobs don't be surprised at all if you get asked to demonstrate UI gesture recognizers what we're going to build today is a simple screen utilizing the UI pan gesture recognizer now this was the most common gesture recognizer I had to use so that's why I'm doing the video on it the screen she's going to be pretty simple you're going to tap and hold on a file drag it across the screen down to a trashcan pretty simple let's get started so like I mentioned in the intro we're basically just going to be able to drag this document image down here into the trashcan I'm going to walk you through the basic setup I have so you guys can recreate it if you'd like all this is this is an image view you can just Google you know file image PNG and you'll find something and then same thing here this is an image view and you can go ahead and Google trashcan image and make it your own I made my background here of this view I just made it dark gray you can make it whatever color you like so again all this is is to image views this file image view is pinned to the top left corner and this trashcan is pinned to the bottom right corner with a height and width constraint one major thing that you need to make sure you do because image views don't default like this click on this file image and then make sure you have user interaction enabled where my mouse is shaking right here clicking it on clicking it make sure it is enabled if it's not enabled your gesture recognizer won't work and this goes to whatever view you're trying to add the gesture recognizer to double check to make sure that's enabled ok so diving into the code basically have a clean slate here the only thing I have is I do have outlets for my energy you set up here on line six and seven alright so start with the basics the first thing we want to do is add our pan gesture recognizer to our file image view so to do that we'll just put it in its own function so function add pan gesture and that will take in a UI view called view so now we want to actually create our gesture recognizer so let's just call it pan let pan equal UI pan and it should autocomplete and then do an open parenthesis to get the initialization target action that's what we want so target is going to be self and then action I'm going to leave blank right now so let's go ahead and write that function so what goes here in the action is a selector for what function you want to write so down here let's go ahead and at least stub out that function so we'll call it func handle pan and this is going to take in a sender and this is going to be the UI pan gesture recognizer that it takes in so again we're just creating that now so we can go ahead and autocomplete our selector up here we'll fill in the code for that in a little bit so hash tag selector through a parenthesis and then view controller and this is whatever the name of your screen is because I'm using the default view controller file for this example it's your controller and then you do dot handle pan and it should autocomplete okay so this line here seventeen has created our pan gesture recognizer now we just need to add that recognizer to our file view so that's pretty simple here but in this function right here we're not actually adding it to our file view correctly we're adding it to whatever view we pass in here to the function so to do that we just do view because again that's the view we passed in dot add gesture recognizer and it should autocomplete and it takes in a gesture recognizer and that's what we just created on line 17 called pan so again real quick walk through line 17 we're creating a UI pan gesture recognizer called pan we're giving it the action of handle pan which we created down here which again is where the bulk of our code is going to go and then once we create that gesture recognizer called pan we go ahead and add it to our view and the viewer adding it to is whenever we pass it into this add pan gesture function here so let's go ahead and do that so call it here in viewdidload add gestures and she takes in a view and then we'll just do the file image view that we have in our outlet above so there we go now if you did load we're adding the pan gesture to our file view good to go okay now let's start coding up our handle pan function down here again this is where all the magic is going to happen the first thing we want to do is get our views so let's let file view equal sender view and what this line does is sender remember is our UI pan gesture recognizer that we created up here and is it is attached to the file image view so essentially what we just did here is we grabbed a variable called file view and that is our file image view that we're going to work with throughout this function now the next thing we want to do is get a variable for our translation now the translation is a property of the UI pan gesture recognizer that tracks the location and velocity of the movement of the pan which is exactly what we want because we're going to be moving the file view across the screen so let's go ahead and grab that into a variable just say let translation equal sender member senders Rui pan gesture recognizer dot translation and then you notice it's translation in UI view so the translation is accordance to the whole view of the screen so that would be just view because this is the view controllers main view that our file image view and trash image view are in so again the translation is tracking the location and velocity of the gesture within the main view on the screen all right now that we got our variable set for our file view in our translation let's go ahead and handle the different states that the UI pan gesture recognizer can be in now there's three main states were concerned with there's the began state when you start your gesture the change state which tracks every movement throughout the gesture while you're still holding your finger on the screen and then there's the ended state which is when you actually lift up your finger so as you can imagine what we're going to do is in the began state we're going to start our movement throughout the change State we're going to keep tracking the movement and animate it and then during the ended state when the finger is lifted we want to check to see if our file image view is intersecting our trashcan view at all and if it is intersecting our trashcan view we'll go ahead and delete that view if it's not intersecting the trashcan view when they lift up their finger we're going to animate that view back to its original starting point which reminds me we need to have that starting point in the variable so up here on line 9 let's go ahead and create file view origin and the origin of the frame of view is going to be a CG point now we know we're going to have that because we're going to set it in viewdidload right away so we can go ahead and force and wrap it with the exclamation point so down here on line 16 let's go ahead and do that so file view origin equals file image view dot frame dot origin now the origin of the frame is the upper left-hand corner imagine if you're looking at a chart you know 0 comma 0 for the x and y coordinates that's what you're looking at for the origin ok now that we got our order to set up let's head back down to our handle pan function here on 25 to 34 what we're going to do now is we're going to handle all three of those cases that I mentioned that began changed and ended of your gesture so for that we're going to use a switch statement so switch can't type switch and going little autocomplete the value that we're going to use is sender remember senders our UI pan gesture recognizer dot state and again that's because it's the states we talked about and actually in this circumstance the code this can be executed during the be game and change state is actually the same so we can go ahead and do this so dot began comma dot change so we're handling both the began and changed in this little block of code and for right now I'm just going to put a break here just so I can finish stubbing out the rest of the switch statement and then we'll go back and change this so the next case in final case we want to handle is dot ended and again just for now put a break statement in there so Xcode will stop yelling at me and then default a break just for now and again during begin and change we're going to go ahead and move the file image view and then ended we're going to check to see if it's in the trashcan or not and we're going to act accordingly all right so let's get rid of this break and then start writing some actual code I like some space here okay so let's handle actually moving our file view so to do that we need to do file view dot Center equals CG points and so what we're doing here is we're basically moving the center of the file view along with our translation which again the translation was the movement of your finger essentially so it's going to initialize the CG point here go down to just make it a float the X&Y coordinate so for X we're just going to do file view dot center dot X so file view dot Center is an X and y coordinate of the file view so we're just going to take the x-coordinate of that center and then what we're going to do to that is add the translation now remember the translation is the basically the movement of your finger during the pan gesture recognizer so plus translation dot X and again just the x coordinate of the translation so that handles our five US senator x-coordinate and basically just do the same thing here but just with the y-coordinate so file view dot center dot y plus translation dot y and now that we have that new x and y cg point we need to go ahead and set that translation so sender dot set translation and this takes in a CG point in the UI view so we're going to do just cg point dot zero in the UI view again is the overall screen view so this is just going to be view guess what these two lines of code are doing are just moving our the center of our file view along with our gesture recognizer echoes yelling us right now because we're not handling this file view optional sender dot view we're here returns an optional you know we're going to have a view here because we're handling it and viewdidload when we added our pan gesture recognizer to our file view so it's okay to force unwrap that and then let's go ahead and do what Xcode says and delete this question mark here we don't need to do any optional stuff here on line 32 because we force and wrapped it up here in line 27 now side note be careful enforcement wrapping X closures going to tell you to force and wrap everything just be very careful when you do it make sure you know for sure you're going to have that object just to prevent some crashes so let's run a real quick alright here we go go and click and drag on our dock alright it's moving cool moving with my mouse let go I mean it's not animating back yet cuz we haven't done that but yeah the gesture recognizer is working we can move it all around you put it on the trash can up nothing really happens real quick if you notice it's going behind the trashcan let's address that real quick so up here in viewdidload on line 17 just go ahead and we'll bring this sub view to front so view which again is the view controllers view that bring sub view to front in the view we want to bring to front is file image view so what that does is just if you're familiar with z-index or anything like that that just basically brings that view as the top layer in the view so now when we run it again we won't do it we'll do it later but the file image view will now be on top of the trash can just a small subtle thing but it'll look better alright let's go and handle our ended state but first I'm going to make a note here we're going to refactor this we'll get into that in a second you'll see as we do our ended view it's not going to be the most readable code I'm going to go ahead and code it the first time like this because it's easier to explain what I'm doing and then we'll take a couple minutes afterwards to go back and refactor okay so clean up some spacing here this looks a little cramped okay so for ended let's get rid of this break again give us some space so the first thing we want to do is check to see if our file image view is intersecting our trashcan view at all so in order to do that it is if file view again this is our variable from line 29 dot frame dot intersects here's the big thing so the frame which is a CG wrecked on a view so every view has a frame and that frame is a CG wrecked and cg rekt has a method to see if that rect intersects another wreck so here we go we'll select that and the other rect we want is trash image view dot frame so this actually reads very well if file view dot frame intersects trash image viewed up frame I mean you don't have to be a coder to kind of realize what's going on there so if that is in fact the case we're just going to go ahead and animate away the file view kind of delete it from the screen so do some quick animation here UI view dot animate with duration going ahead return to figure that out we're going to do 0.3 seconds here return here to get the closure and in the closure we're just going to do file image view dot alpha alpha is the opacity if you're not familiar with that so file image view alpha equals 0.05 it away so let's actually test this real quick oh sorry we need a fear and a closure you need the self self dot so let's go ahead and test that real quick all right so now when we're dragging around our file again it still doesn't animate back we're going to handle that a second and then now if I put it over the trashcan nothing happens because I'm still holding it down we're not in the ended state yet we're still in the changed state so now I'm actually going to let go of my mouse over the trashcan and it should animate away all right letting go the mouse and there it goes it's like I just throw it away cool so now what we need to do is snap it back into place if it's not in the trash cans let's go and handle that so that's just an else statement on this if so again the first part of the if statement is if file view frame intersects trash image view dot frame that's when we'd remove it if it doesn't we want to snap it back into place again we're going to clean up this code a little bit but for now so if else we want to basically animate it back to the origin now if you remember back here our variable here on line 9 that we set on line 16 we have our file views origin so it's pretty easy to animate back so again UI view dot animate same thing here zero point three that return there and the code is pretty simple here so it is self dot self dot file image view that frame dot origin remember we're setting the origin equals and then we're going to call our variable that we set up there file view origin and again I need my self here I always forget that especially what I'm trying to teach my mind is on a bunch of different things but anyway it's going to run this real quick and our view should animate back all right here we are so I'm dragging the document around all right I'm going to let go over here and bam snaps back put it over here snaps back not quite to the trashcans now it's back and then put it on the trash can and it's gone cool so essentially right now we have the working functionality but I want to point out is I mean even even if I clean this up this code I mean it's not horrible to read I mean an experienced developer could probably come in and figure out exactly what's going on however I believe that we want to make our code as readable as possible as someone who has read other people's code sometimes it gets very frustrating when you're trying to like reverse engineer and dissect what exactly is going on so I like to write my code as expressive and easy to read as possible like I mentioned earlier about line 39 I would just read so beautifully like if file view dot frame intersects trash image view dot frame I mean that's pretty self-explanatory so we're going to work on making the rest of our code that easy as well but the basic functionality is complete you have your code if you're just here for that that's all you care about go ahead and the video now you're good to go but if you want to refactor a little bit and work on writing better code stick around for a couple minutes so in order to do this we need to write some helper functions essentially what we're going to do is we're going to takes line 35 and 36 put that into its own function and then take these animations here and put them into their own function so it's going to be much more readable so let's go ahead and do that here so we need to be outside of this original handle pan function so let's make some space here and let's handle the so let's go and create our function that handles this movement so call it func move view with pan that's very self-explanatory you get that this is going to take in a UI view because we need to know what view to move that's our file image view so UI view and it's also going to take in our pan gesture recognizer so we'll just call that sender again and it's a UI pan gesture recognizer and we need our pan gesture recognizer because that's what handles the translation that I mentioned earlier which tracks the movement of the gesture so now what we can do basically is just copy and paste lines 35 and 36 so command X and then down here community we're going to make some adjustments to it and then up on line 30 we need to get our translation down here so command X and then community that down here to line 60 and we actually don't need to change anything on line 60 because it's based off this sender which again we're passing in here on line 58 we do have to change this a little bit this is no longer going to be followed you this is just going to be the view that we're passing in here on line 58 so we can just copy view here if you double click on file view it only high like that and they do come in a V to replace that with view and again everywhere see file view double click it command V file view double click it command V and then here in line 63 we still have our sender up here on line 58 so we're good there and then in view of U so we're good okay so that should handle the movement let's go ahead and now we need some code in here so let's go ahead and call our move view with pan again it takes in a view which we have up here on line 29 let file view let's close up the space a little bit so let's go ahead and throw in file view back in there and sender is going to be sender because we're just passing in the sender here from line 27 which is the UI pan gesture recognizer so BAM we took this chunk of code here on line 60 and 64 and just made it one line right there so you can already see it's super readable now so during cases began and changed what are we doing we're moving the view with the pan what view are removing removing the file view and it's from the UI pan gesture recognizer again super readable so it's going to do the same thing with the animations here I'm going to fast-forward through some typing here okay so all I did here on line 61 through 66 was create a function called return view to origin this was going to animate our view back to the origin if we not in the trashcan it's going to take in a UI view which again is our follow of you from above and all that does is the animate and actually made a mistake copy/paste errors are dangerous be careful when you're copying and pasting I basically pasted this into the wrong one so if you look at this code this is where I'm animating the Alpha so this should be in the delete view so let's go ahead and come in C and then command V down here and then here we're going to go ahead and cut this and then paste it here so I just basically flip-flop that code around a little bit and then okay so let me explain what's going on here so just we have a function called return view to origin it takes in the UI view which is going to be our file view and I just cut and pasted that animation code from above and this used to say file view here I switch this out for view but self dot view is confused now this thinks because it's blue you'll notice that should be the first you know warning sign this thinks it's actually the the UI view of the view controllers so we need to go ahead and get rid of this self here and then same thing down here on line 71 because there's confusion there another way to avoid this confusion is to appear in line 61 here not name this view name it's something else we're in keeping view for now just to save time but that's one way to avoid that error name there's something different or does not have the self here and then here in delete view you guess that we just basically move that animating the alpha to zero code down to here and replace file view with just the view that we pass in because we're going to pass in that file view up here in ended now we have our if file view to frame intersects thrashing review dot frame let's go ahead and handle that code now so if that is the case what do we want to do we want to delete it so we just have delete view and the view we one delete is file view okay again we just took that down to one real quick and simple on a code and then here in the else statement we want to return to origin so just call that return view to origin what view we want to pass in the file view and then we still have our default case so cool we took that tricky code that you saw before and now using these helper methods here on line 50 to 69 we basically reduce it down to a very readable code here with the handle pan so again in case began in case changed we what do we do we move the view with the pan and we're moving the file view according to the UI pan gesture recognizer and when it ends we want to check if file view died frame intersects trash image view dot frame again pretty self-explanatory if that is the case we delete the view what view file view makes sense and if it doesn't intersect the trash view and you let go we're going to return this view to origin again very readable so I much prefer code like this when I'm coming into a code base it's very easy to understand you get what's going on right away rather than having to like really know squint your eyes and dig into the code and try and really figure it out it saves time for your other engineers highly recommend refactoring your code to make it much more readable the only downside is we did add a couple extra lines of code here but in my opinion that's a small trade-off to have very easily readable and understandable code so there you go now you have some clean code and hopefully a better understanding of using gesture recognizers there's your crash course on UI gesture recognizers now you may not get that exact question but the principle Mays the same just know how to move and manipulate objects around the screen using touch and most of the other gesture types are very similar they all have that began changed and ended states that we went over so as long as you understood that you should be good to go alright if you found this at all useful go and hit subscribe I put out new videos all the time
Info
Channel: Sean Allen
Views: 36,751
Rating: undefined out of 5
Keywords: Swift Pan Gesture, iOS Interview Questions, iOS Interview, Swift Gesture Recognizer Tutorial, pan gesture swift, pan gesture recognizer, pan gesture recognizer tutorial, pan gesture recognizer swift, Swift, Swift 3, iOS Development, iOS Developer, Learn Swift, Swift Tutorial, Xcode, iOS Tutorial, Xcode Tutorial, Software Interview Questions, Software, Apple, iOS
Id: rnJxpuPyLNA
Channel Id: undefined
Length: 20min 18sec (1218 seconds)
Published: Sat May 13 2017
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.