iOS Tutorial (2020): How To Make Your First App

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] hello and welcome to how to make an app for beginners in this video I'm going to show you how to make an app even if you've never programmed a single line of code before now by the end of these next 10 lessons you'll have built these apps and user interfaces and I'll also show you how to put them on your phone so that you can show your friends and family but more importantly I'm going to teach you the fundamental skills that you'll need to build any sort of app so by taking these beginner lessons you're going to get a really nice and solid foundation in iOS app development from there you'll want to grab my free seven-day app action plan where you can create a customized app roadmap just to build your app you also want to join our active Facebook community where you can get help and support from myself and the team and tons of other people learning iOS just like you so that you're never stuck or alone on your journey to create apps now the last time I taught this it was viewed by over 1.2 million people and tons of success stories came out of it ton of people created their own mobile apps as you can see some of them on the wall behind me now I know that's all going to come for you too but it all starts right here right now are you ready let's do it welcome to code with Kris the place to be if you want to learn how to make an app I'm Chris and I'm so glad you're here first things first how do you create an app from scratch well it all starts with a program called Xcode where you design the user interface for your app and write your code that gets turned into an iPhone app which you can publish to the App Store where millions of people can download and use it before that let's backtrack a bit though Xcode is a program you can download for free and the code I'll be teaching you how to write is called the Swift programming language don't be intimidated if you've never coded before because I guarantee you'll get the hang of it next Xcode can only be installed on Mac computers but if you don't have access to one you do not need to spend thousands of dollars to buy one instead check out my video on Xcode for Windows using Mac Stadium first alright so with that out of the way let's dive in and let me show you around Xcode so the first thing you're going to want to do is to download Xcode if you haven't already and all you have to do is hit command spacebar on your keyboard to launch spotlight type in App Store to launch it and then in the search bar type in Xcode and that's going to find it now I've already got it installed so if you don't you want to go ahead and do that I'm gonna warn you though it's a pretty big application so it does take a little while to install and if you can't if it gives you an error message or something like that scroll down check on the compatibility if you click it it tells you what version of Mac OS it needs for this one it needs ten point thirteen point six but whenever they upgrade Xcode this number gets higher and higher so your you might have to update your version of Mac OS in order to install Xcode also keep in mind the size here even though it says 6.1 gigs it sometimes needs a little extra space in order to do the installation so once you have it installed go ahead and open it you're gonna be greeted with a dialog like this what we're going to do in this video is create a brand new Xcode project so click on create a new Xcode project if you don't see that dialog for some reason maybe you've launched Xcode before you can always go up to file go to Neal and choose project and that's gonna get you to the same place now there's a bunch of different templates that you can start with to help you just be a little quicker in terms of what you want to create what we're going to want in this lesson is to be under this iOS tab because there are different platforms you can build for using Xcode and Swift which is the great thing about learning these two things but we're going to do i OS today and we're going to choose single view app and that's going to give us our basic one-page app or one screen app next we're going to want to configure some of the options for our new projects such as what the name is what the unique ID of it is and for the product name you can name it something I'm going to choose hello world like that the team drop-down you might not have a team here and that's not going to matter right now but you will want to create a team when it gets to the point where you want to put the app your actual device and I'll show you how to do that later on in the series organization name I would either put your company name or your personal name and then what's common under organization identifier is comm dot and then your name or your company name so combined with the product name that's going to be the bundle identifier you're gonna see this term used quite a bit it's basically like the unique ID for the app that you're creating when you publish your app when you upload it to the app store in that sort of stuff you're going to need that bundle ID okay so next very important is to make sure your language is set to Swift because that's what we're learning here you can leave these guys unchecked and then click on next and you can also leave source control unchecked as well we're not going to go through that right now go ahead and click create and you're gonna have your brand-new Xcode project now it kind of looks intimidating because there's all these checkboxes and dropdowns and you know this interface to someone who hasn't seen it before is pretty confusing but I'm gonna walk through it with you right now and I also have a reference sheet for you with a diagram and all the keyboard shortcuts for Xcode so make sure you grab that in the description below so we're going to start on the left hand side of the interface and this is the Navigator area you'll notice across the top that there are different tabs that you can click it might not be so clear in the beginning but these are different navigators that you can choose by far the most common one you'll be using is this project navigator where you can see all of the files in your Xcode project now clicking on any of these files will change what's in the middle that's called the editor area so for instance right now we have this first project file clicked on and that's why we see all of the project properties in the editor area if we click on View controller the Swift you're going to see that this turns into the code editor so that you can write Swift code go ahead and click on main dot storyboard and this is going to change into an editor where you can customize the screen for your app we're going to be doing this shortly this is actually called interface builder so you can kind of get what why that name is the way it is next let's go to assets the XE assets this is where you're going to put all of the images for your project that you're going to use and then launch screen dot storyboard is another sort of interface builder file where you can customize the launch screen and then the plist has some further properties for your project at a high level those are the files that by default are included inside your Xcode project now moving along to the right side of the screen we've got the utilities pane and what you see here depends on what you're clicking on inside of the editor area so it's like a further drill down so for instance if we go into the main dot storyboard and I click on this white area which is my view or my screen it's going to show me further details about that and in the viewcontroller.swift if I click on let's say some piece of code then it's gonna tell me something related with that but keep in mind that again there are some different tabs with this utilities pane as you can see up here so if we're going into the main thought storyboard you can see that there are a couple more tabs and that's because I can configure properties for this element so it looks like Xcode has experienced an internal error but usually these are fine you can just close the project and we launch it I'm not going to do that right now it's fine across the top of the interface you have your Xcode toolbar now on the left side of the toolbar you have some buttons to run your project and stop your project and then to the right of that this is actually a drop-down where you can select the destination on which to run your project now if you plug in your phone you can actually select your phone from that drop-down but if you don't have a phone plug then don't worry because Xcode has a bunch of simulators where you can run your project on and it's going to show it on the screen we're gonna do that in just a second in the middle here you have your status bar it's gonna show you what's going on with your project what it's doing right now and then on the right hand side there are a couple of more controls here which we're going to get to in a second but in the rightmost part of that toolbar you're gonna see these buttons which are really helpful to you right now it's just to hide and show these different areas that we're talking about if you click this middle one you'll notice that it brings up this little tray down here that we really haven't talked about yet and this pane down here is called the debug console and when you're running your project and let's say an error happens you're going to get some details about that error in this debug console so by default it's hidden if you want to show it all you have to do is click this button to bring it up so these are the major sections of the Xcode user interface it's not that complicated once you know right what we're going to do now is go ahead and run our project on a simulator so in that drop-down that I showed you by default right now it's iPhone 10 arm you can select any one you want to try out and just click this big play button right here it's going to launch that the Iowas similar now the first time you do this it might take a couple of minutes but then subsequent times is going to be a lot faster after the simulator has launched so you actually don't really need a physical iPhone device if you don't have one you can still build and test your app now there's one quick thing I want to mention and that is if your simulator is way too big for your screen and you can't see all of it you can actually scale it down so you can either go up to the menu of the similar and choose you know physical size or point accurate or pixel accurate you can use these shortcuts command one command two or command three to change the size of the simulator that you see so just a handy tip for you in case the simulator is way too large for your screen so when your app has launched you're going to see this white screen and that's because we haven't really added anything to our app yet but before we do that let's talk about how that Xcode project turned into this app that I'm seeing in the simulator this top layer is the view it's the screen that the user sees now you can configure this V from the main storyboard file in your Xcode project the second layer under that is called the view controller now this code file is responsible for managing the view for instance when the user taps on the view it's going to let the view controller know and then you can write code inside that view controller to handle that tap to either run some process in the background or maybe display some new information on the screen you get the idea now this view controller is represented by the view controller dot Swift file in your Xcode project and as we said before if you click on that file the editor area turns into the code editor where you can write Swift code to manage the view now if your app has multiple screens in most cases each screen is just going to have its own view and view controller now let's go back into Xcode and we're going to stop our project and we're going to add something to the view so that there's something to see let's hit on the stop icon right here and then click on main storyboard so you're seeing the interface builder and now I'm going to introduce you to this button here called the library button so if you click this it's going to bring up a list of objects or UI elements that you can add to your view type in the label to search for this guy and all you have to do is click and drag it onto your view like this now you're going to see that label on your view right here now you can drag it around and you can position it but that's not really going to do anything because Xcode actually has its own way of positioning and sizing layout items Xcode uses a system called auto layout to position and size the elements on the screen this system makes it easier for you to design a single interface that looks good on iPhone iPad and all the other screen sizes of future iOS devices now basically all you have to do is specify a list of rules for each element that dictates how it should be positioned and how it should be sized relative to other elements on the screen for example this element should be the same height as this other element or maybe this element should be centered on the screen these rules are called constraints and in lesson two you're going to learn a lot more about Auto layout and Auto layout constraints but for now let's jump back into Xcode and take a look at how we can position and center our label on the screen all right so back in interface builder I want you to select your label just to make sure that it's highlighted and then down here there are a couple of buttons where you can add Auto layout constraints so click on not add new constraints but this button called a line because we want to basically align this label in the center of the screen so we're gonna check horizontally and vertically in container and then click Add to constraints and you can instantly see these lines here that represent the constraints you just added as well as the label being centered on the screen if you've made an error don't worry check it out right here this is called the document outline and it basically shows you all of the elements and all of the constraints that are in your view right now so just open up constraints you can highlight your constraints that you've added maybe you've made an error or something like that you can either delete them right now I can hit delete and get rid of them or if you highlight them in the utilities pane on the right hand side in this size inspector or they there's different inspectors that you can select make sure that you're looking at either the attributes inspector or the size inspector and then you can edit some of the properties for your constraint I'm going to show you just the leading them right now off of the document outline so they're gone I'm going to do it again so you can hit your label now and you can go into a line and select horizontally and vertically in container and then add two constraints like that the next thing we're going to do is we're going to edit that word inside the label so make sure your label is highlighted and then on the right hand side again make sure you're looking at the attributes inspector right here under text you're going to be able to just type in whatever you want I'm gonna type in hello world and voila so click on the Run button on your Xcode project and it's going to launch simulator once again and you should be seeing something that looks like this congratulations you built your first step to get a copy of the recap notes of what we went over today as well as some practice exercises just click right over here or find it in the description below in the next lesson you're going to be building this in Xcode hello in this video I'm going to teach you how to build user interfaces for your apps using Xcode Auto layout system now if you want to know how to build cool you eyes like these then the Auto layout basics I'm going to teach you in this lesson or absolutely critical to know and if you watch all the way to the end you're going to have a really good idea of how to build your own user interface for your own apps does that sound good let's do it alright so let's pretend that we have to build a login screen for our app we're first going to start by doing it the old way and then we're going to jump into Xcode and use auto layout and do it for real now our first task is to place the logo on the screen Xcode uses an XY coordinate system where 0 X and 0 Y is in the upper left corner so this point would be 0 X and 0 Y or just 0 0 next take a look at this red dot this represents a location on the grid at 10 10 so you kind of get the idea if you specify a logo to be placed at this point at 10 10 then it's going to take the upper left corner of that logo and put it at that point now next you can specify a height and a width for that logo and that's going to adjust the size of it now together with the X the Y the width and the height that is called the frame of that logo element now you can continue to use this approach and place the rest of your labels text fields buttons whatever you need however when the login screen is shown on a much larger screen if not going to look the way that we expect and this is where Auto layout comes in so instead of specifying exact XY coordinates widths and Heights we specify rules to describe the location and sizes of all of the elements relative to other el and these rules are called constraints now why don't we try redesigning this login screen using auto layout constraints instead so here's our first login button I'm going to add a constraint to say that the horizontal center of this button should be the same as the centre of the view in terms of the x-axis so that is going to Center it on the screen on that x-axis now I'm going to add another constraint to say that the button should have the same vertical Center as the view and that's going to Center it vertically on that y-axis now this effectively puts the button right in the center of the screen next I'm going to add the logo and I'm going to add a constraint to make its horizontal center the same as the horizontal center of the button so that's going to be aligned the two elements like this I'm going to add another constraint to that image and this time we're going to say that the bottom of that image should be 20 points above the top of the button now notice I said points and not pixels and that's because in iOS we have devices with different pixel densities so for example on the original iPhone one point is one pixel they're one and the same but then Apple introduced Retina screens where they managed to squeeze four pixels in the same amount of space that used to be one pixel so on these screens one point is equal to four pixels and then Apple introduced the super Retina screens and these are for the plus sized iPhones where they managed to squeeze at nine pixels in this space that was once one pixel and so one point on these screens equals to nine pixels so that's why when we're designing our user interface we always speak in terms of points it allows us to have a consistent user interface regardless of the pixel density of the screen that it's being presented on so when you say 20 points from the left side it's going to look consistent on the original iPhone on a Retina screen or a super Retina screen now if this is kind of confusing to you don't worry because you're never really gonna have to worry about how many pixels things are you're always working in terms of points but I think that it's important that at least you know about this distinction now another thing I want to point out is that if I don't specify a specific height and width constraint for this logo then it's going to just be set at its intrinsic size which is just whatever size the image is if you wanted to you could add constraints for the logo to make its height in width relative to other elements or even relative to the screen size but I'm just going to leave it as is now I'm going to do something similar with the second button that we're going to add I'm going to add two constraints want to say that it has the same horizontal center as the first button we're just going to align the buttons together and then I'm going to add a second constraint to say that the top of the second button should be ten points below the bottom of the first button just so that they have a ten point gap now we're going to add the last button to constraints again one for the horizontal center and the second constraint to position it ten points below that middle button since all these elements have constraints that are relative to that first button if I move that first button around then all of the other elements will follow because the auto layout system is going to find a way to satisfy all of the constraints that you have added now there's a much easier way to achieve the same thing that we have here without having to specify so many constraints and I'll show you how to do that in lesson 3 for now though I think it's important for you to understand how Auto layout constraints work which is why we are doing it this way now let me ask you do you feel like being a bully today because we're going to be really mean to this logo right now why don't we add another constraint that contradicts an earlier constraint we added so let's say that we add another constraint to this logo to say that the bottom of the logo should be ten points from the top of the first button now notice that this contradicts the earlier constraint that we added that said that it should be 20 points above that first button so there's no way that it can satisfy both of these constraints that we've added this is called conflicting constraints and the system will actually choose constraint to break and this can lead to unintended layout glitches so the tough part of working with Auto layout is just to make sure that you don't have conflicting constraints because sometimes as you're adding these constraints in inside Xcode you might lose track of what you've already added and when you finally run your application you might get a bunch of conflicting constraints and the auto layout system will choose which ones to brake and the layouts not gonna look like anything you intended it to now Xcode does give you tools to help you manage and resolve these conflicting constraints as you're soon going to see because the next thing we're going to do is we're gonna jump into Xcode right now and construct this login screen for real now there's one thing that I want to quickly point out and that's when you start your Xcode project you don't have to turn on Auto layout or anything like that to use it in fact it's just the standard when you start a new Xcode project you're gonna be able to just start using it right away so I've got a brand new Xcode project here using the single View application project template if you're not sure how to start a new Xcode project and I would say watch lesson 1 as we go through that in that lesson what we're going to do is jump into the main dot storyboard and we're going to get started we're gonna hit command shift + L and that's going to pop up the object library menu or you can just click on this guy up here and you can search for button here click and drag it right there and to add a button on the screen and I want you to click on this align menu and choose horizontally Center in container and add that one constraint that's going to Center that button but you'll notice that there are some red lines above and below that button and also in the document outline here you'll see this red arrow if you don't see this document outline just click on this little icon here to open and close it so anyways I want you to click on this red icon and it tells you that the system doesn't know how to position that button on the vertical axis because there's no constraints to dictate how to position it so I want to do and you can see here the category for the error is missing constraints they'll go ahead and click back but just before we add that constraint there I want you to notice another thing and that is to click the button click on this align menu and don't be alarmed that this horizontally and container item is not checked but you might ask we just added that why is that not checked well the reason is because these menus down here are purely for adding new constraints it doesn't consider what constraints are already been added to that element in order to see what constraints you have added to that guy you can either click the button and go into the size inspector and you can scroll down a little bit under constraints you can see that we have this align center X constraint or you can open this part up in the document outline and you can see that we have this constraint in fact if you highlight that constraint right now I want you to go over to the attributes inspector and we can take a look at the anatomy of a constraint the main things that you need to notice is that an all-out constraint relates to one element which is the first item and how it is going to be related to the second item in which case here it says super view dot Center X so what the super view means is it's just the view that contains that particular element in this case that is going to be our overall screen or our view and so the buttons the super view or another way to think of it is parent view is the view the screen itself and the properties it is relating is the center X all right so the button Center X is equal to the super view Center X and effectively that centers the button on this screen right here and then you can also play with things like the constant priority and multiplier and these just gives you a couple of different ways to manipulate how it is related to that second item in that constraint but we won't go through those right now so go ahead and highlight your button let's add that positioning on the vertical axis click on a line right here click on vertically in container and boom right there you wanna notice that we have two constraints now for that button and if you click on this button and go back to the size inspector you're gonna see that second constraint there so this is a handy way to see all of the constraints that are related to that element because in here this menu this can get quite long once you have many items on the screen all right so that's going to represent our first button we're gonna add a couple more now so go either use the shortcut key to open the object library or click on the button up there they add our second button click on a line horizontally in container and we're going to have this second button relative to this first one by 10 points right we're gonna leave a 10-point gap there so click on this button and then click on this add new constraints menu and it's going to have a couple of margins that you can set for to be exact you can enable or disable any of them just take note that if you edit one of these margins that's automatically going to turn on that constraint and then you can see it says add one constraint here so I want you to pull down the menu and you can see for this button that you're adding the constraint to what do you want that second element you know the one that it's going to be relative to what do you want that second element to be since we want this button to be ten points below this first button we're going to make it relative to that first button right so that's why you got to pop open this menu to make sure that this is selected so when you select that it's going to change the value to what it currently is so currently it's thirty three point five points away so just take note of that right for example if we did view and we did you know ten points away that would actually make this button go all the way up here and be ten points to the ten points from the top of the view right which is not what we want so make sure you have the right element selected and click add one constraint and you can see there that constraint that we added right there this button is top is equal to the first buttons bottom and the constant is 10 so that's where the constant comes into play now this is starting to get confusing because they're both named button what we should have done to make it a little more clear as we could have renamed things like that let's say first button in the second button and now you can see the auto layout constraints they change the names too so that's really handy to see now if you click on this constraint that we just added the second buttons top is equal to first buttons bottom by 10 points so that makes a lot more sense now let's add our last button right here again we're gonna align it first horizontally in container and we're going to add a new constraint and we are going to click enable that top one and we're going to make it relative to the second button by a factor of 10 points again boom that lines it up right there let's not forget to name this guy our third button so we've got our bunch of buttons there now we're gonna put a logo but the local is just going to be a text label in this case and we're also going to add a little little prompt a little instruction label above these buttons actually so let's do that press a pop it open again I like I instinctively know what the keys are but my hands know right but then if you ask me to tell you I have to look down at the keys first so command shift and L and that's actually one thing that now that we're on this topic I want to tell you about is is just muscle memory right so you know at first when you're learning this stuff you're going to be slow and especially when you start learning Swift and you're you're gonna start learning the syntax you're gonna try to memorize keywords and you're gonna try to memorize things but you don't really need to do that all you need to do is just build more apps go through more demos go through more tutorials and your fingers almost they have a mind of their own so your mind thinks you know I want to open up that object library and your fingers they just kind of like know what to do your hey you don't have to think I need to press command shift and L initially it will be like that but as you do it more it's just going to be very instinctive so I just want to I just want to point that out don't get discouraged if it doesn't come easy in the beginning now I added this right here and you'll notice that there's a yellow error now it's not red like before red man error yellow instead means this this element doesn't have any auto layout constraints so why don't we position this also we're going to position it horizontally in container and we're going to specify the bottom margin this time and we're going to say that it's going to be relative to the first button by 20 points right actually I want to show you one cool thing and it's gonna save you a lot of time hopefully so let's say that I when I dragged my label it was over here it was like almost on top of that first button and you know I want to position it relative to that first button by 10 so I go go ahead and enable that constraint I hit 10 pull down this drop-down but the first button isn't there I can't choose the first button in this drop-down why is that well the reason is because your label is overlapping that first button so it doesn't come up as a neighbor here so you need to make sure if you want to make you know an element relative to another element you have to make sure that they're not overlapping and sometimes they could still be overlapping even though they don't look like that in the view because we mentioned the frame earlier in this lesson if you check this button out you can see that the frame actually then and beyond just the word button you can see these these white dots here that's so that's part of the frame so even if the frame of the label is kind of touching the frame of the button and you know it's not like the text isn't overlapping but at this point they could still be overlapping in fact yeah they are and so I won't be able to see that first button but if I just drag it out a little bit more I can then choose the first button so hopefully that saves you a lot of time because you might not realize that in the beginning so let's add that one constraint boom that's right there another cool thing is that let's say i drag this away you can see these lines they kind of turn orange right now and that's basically saying that the auto layout constraints for that label they aren't taking effect right now because you're like dragged it away so what you're seeing on the view is not reflective of the constraints that you've added to fix that all you have to do is click this little update frames button that's going to just run all the auto layout constraint rules and that's gonna put everything where they're supposed to be according to the constraints that you have added all right so this this label we want it just to say log in or create an account that's kind of what I wanted to say at least okay we're going to add another label I'm gonna drag it like that I'm going to put it in the center and we're gonna position this guy bottom constraint relative to this label right here and I'm gonna say something like 30 and this is just just me making up stuff right now so I'm gonna call this social squid and in order to put this in two lines what you can do is actually change the number of lines from one change it to zero and that actually means multiple lines now inside here in this label you can actually do line break if you just press control enter you're gonna be able to put a line break and we're gonna Center this and we're just going to change the font now you might not have a veneer next and that's completely fine next let's add some text of these buttons so this one is going to be sign in with Facebook sign in with the rule with email now I want you to notice that you can add an image to these buttons and that is going to add a little icon beside the button or you could also add a background image which is what we're going to be using and you can set background colors and stuff so you can really go in depth with customizing your buttons but because this is an auto layout lesson I want to focus on auto layout constraints and that sort of stuff and not customizing buttons so I've actually prepared some graphic assets just to get the look in the feel of the button that we want without going too deep off the deep-end on customizing buttons so what I want you to do is grab these images and these images I've made available either in the link in the description below or you can click on the upper right corner and you can download these resources so that you can follow along so after you unzip the file and you grab these asset images to strike the mintu here and just the quick note if you don't understand why there are like three sizes of each image one X is the original size 2 X is 2 times as large and 3 X's you know 3 times bigger the reason is because there's different resolutions of the iOS screen so all the retina screens will use the 2 X and the super retina ones would use the 3 X that's why there are 3 different sizes and the right size will be used depending on what screen the device the user is using so like I said these button graphic button graphics I added this rectangular background solid color to it you you know technically could have just customized that and in fact if it were like a production app I would wouldn't recommend exporting your graphics like that but like I said this is for the sake of because we want to focus on Auto layout sort of losing my words here so what I want you to do is highlight the 3 buttons by holding shift on your keyboard and clicking all three and then choose alignment left and that it's not gonna do it oh actually no that's fine that's fine all right that did do it it's just that they didn't align left because the size the width of the buttons are variable right now so I want you to click on that first sign in with Facebook button and change the background to Facebook and you can see it's gonna balloon up we're gonna change that text color to white so you can actually see it and you can actually adjust the the text inside that button by going into the size of inspector and just setting the content insight to something like 20 for example so let's do the same thing for the Google button but let's just change the background image first and then in here we'll just change the content inset and then we will change the font color to black and so sign up with the email the email image change the text color to black and change the content in set to 20 and then we are going to add a background to this so search for image view and all I want you to do is just plop it anywhere it's just going to cover something and I want you to choose background and then I want you to hit this adding constraints and we are going to enable all four constraints and we are going to change we're going to unconstrained to margins now I'll explain to you what that means in a second and we're change these all to zero so by default there are margins for text for example and because we want the image to go like edge to edge ignoring all the margins you know to all four sides of the screen we are going to uncheck constrain to margins another thing to note is that there is something called a safe area and because you know with the new eyePHONE tens there's like a notch so the safe area is just an area where nothing will get obscured no matter what device you're using so if you want like let's say you're laying out text then you definitely want to stay within the safe safe area so how do you stay within the safe area well by default all the constraints you add will be relative to being in the safe area if you don't want to be in the safe area so for this image we want it to go edge to edge we don't want to go under the not like we don't want to leave any gaps on the to the left and the right of the knotch and so we want to go all the way to the top of the screen we would pull this drop down and then we would say relative to the view you can and notice that changes the number back to 72 so just click all of these dropdowns here and choose view instead of safe area so we want to choose view okay and change these all back to zero okay and now add four constraints and that is going to stretch it all to all four sides now if you accidentally made a mistake that's not a problem just go into the size inspector for this background and here are the four constraints you've just added double-click any of them and that's going to highlight the constraint and then in here you can pull down the drop-down and you can say you can choose super view instead of safe area so that's how you would fix it or you can just delete the constraint andrey add them now the problem here is that our image who is covering everything and that brings me to another important point which is layer order now if you look at this document outline this is also called a view hierarchy and the reason it's a hierarchy is because some of these elements they allow you to put other elements inside of them like they're a container element just like this view is this view this what represents our screen here contains all these buttons the labels and this background image well you can have other container views and you can have like multiple layers so it becomes a hierarchy and anything that is closer to the bottom of the hierarchy in the same level is closer to the users so for example this background image right it's all the way at the bottom of this hierarchy at this level and that's why it's the closest to the user and it's covering everything else we want this background to be at the back right we want everything else to be on top of this background so all we need to do is click and drag this guy and reorganize it to the back so now you can see we've just pushed it as the back element you can ignore the safer area here actually actually if you click this you can see where the safe area is but anyways that background now is that backmost element and so all these elements are above it now that we have our layout looking kind of like what we want I want to quickly talk about conflicting constraints so why don't we do that example that we did earlier by making this logo adding a second constraint so that it is relative to this guy but 10 points away from that guy in you keep in mind there's already a constraint that says it should be 30 points above this label I'm going to add a second conflicting constraint to say that it should be 10 points and instantly you can see that there's an error illustrating that there are two constraints one says 30 and one says 10 and if you click down here you can you click this little error icon here you can see there's conflicting constraints so what you can do you can just delete one one of them right so you can't actually delete it from here but you can highlight one of them and just delete it that's gonna fix the problem so also when you run your app and if there are conflicting constraints it's gonna tell you in the debug console in this area down here okay so how do you check if your layout looks good on multiple devices well there is this little option here it says view as iPhone eight you can actually click this guy open and change the device you're viewing it on so let's say 10 R you can change the orientation and see that it is a little squished although you can see everything and there are certain things that we can fix up pretty easily and some things where we're gonna have to add constraints to fix a specific device so in order to give you finer grained control of how your UI looks on different screen sizes and devices there is something called size classes and they're kind of like categories of devices so because Apple has created so many different sizes of iPads and iPhones while you can't configure them specifically for a device you can configure your UI specifically for a size class or a category of devices and Apple has organized all of their different iOS devices into different categories so we're not going to get into size classes right now because this lesson is already running kind of long but I do have a bonus video for you that we will go into size classes and I'll tell you what they're all about and how you can set Auto layout constraints for specific size classes but not other ones so that you can change the look of your UI depending on whether or not you have more space or less space so you can do that it's not it's not a requirement right now we don't really need to do that but if that is something that you're interested in right now you can go grab that bonus training now autolayout is just one of those things that gets a lot easier the more you do it so I've got three practice exercises for you to do and also another bonus auto-layout training video that you can watch you can grab all of these resources right there in the next video I'm going to show you a specific UI element that's going to allow you to reduce the number of auto layout constraints you need to add it's going to speed up your design and construction considerably hello today I'm going to show you how to use an element called the stack view which is going to save you a lot of time when it comes to building your user interface now in the previous lesson I showed you how to use auto layout constraints to lay out all of the elements in your user interface however using a stack view is going to dramatically reduce the number of constraints that you need to specify if that sounds good then stay tuned alright so we're going to redo that social login page except this time we're going to use stack views and you'll see how easy they are to use this time we're going to create a single view app I'll take you through this process I'm just going to call this the stack view exercise and these settings are kind of the ones that we've been using throughout here so I won't go through them again right now but if you're a little confused about them go ahead and check out lesson one alright so we've got a brand new single view application we're gonna jump right into this storyboard and I want to show you what the stack view element is all about so go ahead open up the object library either clicking this button here or hitting command shift and L and let's take a look at actually first what the stack views are so we have a horizontal stack view and a vertical stack view and just as the name implies the stack view is a container element that allows you to put elements inside of it and it's going to arrange in the stack either vertically or horizontally so you don't have to you know if you already you want to arrange elements let's say vertically one on top of each other you don't need to specify a whole bunch of Auto layout constraints to arrange them nicely and align them together and all of that stuff you can just use a vertical stack view throw all of those elements inside configure the stack view a little bit in the stack view will handle everything else so let's take a look at that I'm gonna drag a vertical stack view right there and you can't really see it aside from this outline in fact if you click out of it it's invisible because like I said it's a container element so it by itself is not really a visible element however you will see it here in the document outline and this is a very important point because since it's invisible on the screen as you're adding labels or buttons or things into your stack view it's kind of hard to drag them into the stack view when you can't see it in the view right and so usually if I'm adding elements into the stack view I'll drag it directly into the document outline so let me show you what that looks like we're gonna go grab a button and we're gonna just drag it directly into the stack you and as you can see with a little movement of my mouse that little blue line either indents into the stack view or if I move it out a little it will become an element that is at the same level as the stack view and if this is the case then this button is not inside the stack view it's in fact on top of the stack view so in order to make sure that this button is inside the stack view you need to just drag it and make sure that it looks like this so that you can collapse and expand the stack view and you can see the button element inside of it let's add another element just so we can see some stacking going on like that so I've got two buttons I'm just gonna add a third one right here so now this stacking has three buttons and you can see I didn't put any auto layout constraints on these buttons all I did was add them into our vertical stack view and it's stacked them one on top of each other very nicely now some of the properties that you could configure just to go over them quickly with your stack view is you can change the axis so changing them to horizontal puts them side-by-side and changing them vertical just puts them one on top of each other now this means that when you're adding your stack view and you're choosing it from the object library it really doesn't matter whether you choose horizontal or vertical because they're both configurable to be either one and so you know this vertical stack view here all you need to do is change the axis if you wanted horizontal now here are a couple of more fine-grained controls for how to position your elements inside for example I can just say spacing of 10 points that's going to put 10 points in between each element I can say 20 as you can see it's just going to do that really simple really easily now if our stack view was a little bit of wider for example if we stretched out the stack view to the edges of the screen then I can show you what these are in fact why don't we do that so we're going to grab our stack view here and we are going to we want to vertically align it in the container and then we are going to stretch out the stack view 0 0 on the left and the right so if I click on the stack view you're gonna see that well that's the button right there but the stack view yeah I can't really see the frame here but I've stretched that out 0 0 to the side and you can tell because if you click on a button you see that button with its all the way from the left to the right edges so the reason why this button is stretched out all the way to the left and right sides is because of the alignment property that by default in the stack view is set to fill so let's talk a little bit about alignment and distribution inside stack views these two properties do take a little bit to wrap your head around because what they mean changes depending on whether you're looking at a vertical stack view or a horizontal stack view so let's talk about distribution first in terms of this vertical stack view we've got this much space you can see the white segment here and we've got three elements inside stacked one on top of each other well distribution is basically it basically means how do you want to distribute the space to these three elements right in terms of how they are stacked vertically on one hand we could give each of these elements an equal amount of vertical space on the other hand you know in the case that each of these buttons is a different size let's say they're a different height we could use fill which means that you're gonna give the first element whatever amount of space it needs and then you're gonna give the second element whatever amount of space it needs and then the third and fourth and so on and so forth so each element kind of gets the amount of space that they need in our case all three buttons are uniform so whether we choose fill or to fill equally it looks the same fill proportionally equal spacing an equal centering are also other options they're just different ways of distributing the space and it's kind of hard to explain so you I recommend that when you do the exercise for this lesson just play around with these options take a look at what's different about them but the best way I think to think about distribution is how do you want to distribute the space for the elements inside your staff you now in terms of alignment I always think of that like a word processor so let's say you're you're writing a word and you're writing a paragraph and you can either left justify it you can Center it or you can write justify it well alignment is the same so right here by default it's set to fill which is why it stretches out that button to fill up the entire space of the stack view so that's what fill means if you chose leading center or trailing it wouldn't stretch out the element instead it would either left justify it center or or right justify it so I can show you that lets see leading makes it go there this is centering and this is trailing okay so let me set this back to fill now the tricky part of this is when you set the axis to horizontal then this meaning changes a little bit right so distribution on a horizontal stack view is still how do you want to divvy up that space for each of the elements in this case fill looks a little differently you can see it it still means that it's going to give the first element all of space it needs second element all the space it needs and then whatever space is remaining for the third element if I chose fill equally it's gonna give an equal amount of space horizontal space that is to each of those elements and alignment now becomes do you want to fill out the vertical space for each of these buttons or do you want to top align it center align it or bottom align it so when you're using stack views you have alignment and distribution that you can play around with to basically get it looking the way that you want so now what I'm going to do is try to recreate that social login screen I'll show you how to do it without having to specify so many auto layout constraints like we did in the previous lesson we're going to use a stat view to make it a lot easier so let me first remove the constraints that we added to the stack view so we're going to delete those three constraints and we still have three buttons inside the stack view and what we're going to do is we're going to add the image assets and you can download these in the link in the description so these are the same assets we used in lesson two so let's use these buttons and let's set the background image for them so this one was Google and this one was email and this said sign in with Facebook and text was wiped so in order to align these buttons one on top of each other I just have to change the spacing to ten which is what we had in the previous lesson and to align all of them together well all I need to do is just I can Center this stack view on the screen just like that so all I've added are two auto layout constraints to the stack view but other than that the stack view is taking care of all of the arrangement of these buttons inside and so I think what we also had was a label here and yeah so this label is going to give this equal space here I might not necessarily want that choose a sign in below I forgot the exact wording that we used but that's okay so if I didn't want to give so much space vertical space to this label then maybe instead we can try using fill right instead of fill equally so you can see clearly the difference in that distribution setting right there now for us for the logo and because I want the Loco to have a lot more space between the label this label here and the logo above I don't want to necessarily place the logo into the stack view because in this stack of you I can just choose a blanket spacing and that's going to give a spacing of 10 everywhere so instead what I'm going to choose to do is I'm gonna put the label above the stack for you right there oops let's undo that let me drag this label up here so I want to put this I call this social squid change the number of lines to zero right and I'll Center I like this and just change the I'll change the font to custom and change it to like a bold type of font and this one I will just horizontally align it and I will make it like maybe 40 from there so it's gonna look like that because I want there to be a spacing of 40 instead of 10 that's why I don't want to put this label inside of the stack view because otherwise you know I wouldn't be able to I wouldn't be able to have this bigger spacing here and lastly we need to at the image view and you notice that I'm dragging things into the document outline now and sometimes that's just a lot easier to do so I'm going to set the background image view to the background image asset that we have and I am going to uncheck constraint margins and I'm going to choose view I explained why we do this in the previous lesson it's because we want it edge to edge regardless of margins or anything like that and then let me set all of these to 0 let me add the 4 constraints so we have this image now and furthermore because it's stretched like this I'm going to change the content mode to aspect fill and that is going to maintain the aspect ratio of the image while filling up the entire image view and so we've got something like this so now that you know how to use stack views and auto layout constraints we're ready to build the UI of our next app the war card game as always I have recap notes and an exercise for you just download it right there below hello and welcome to lesson 4 equipped with your new skills in Auto layout and stack views it's time to put them to the test by the end of this video you'll have built the user interface for your war card game app so let's get to it so we're going to start with a brand new Xcode project just click on create new Xcode project right here or you can go into the file menu and choose new project now make sure you're looking at io s and choose single View application here we're going to put the name of our app and this isn't the public facing name it's just something that is going to give you a unique identifier combined with your organization name and your your organization identifier it's gonna create this bundle ID and I talked about this back in Lesson one and how it's going to be really important for an app that you're going to publish it in the App Store now for this app make sure you choose swift as the language you can leave these unchecked and when you save it you can also leave this unchecked as well for now so let's create our project on the desktop the first thing we're going to do is to jump into the asset library for our project and I want you to go and grab the image assets now you can do so in the link in the description below or just check the card just going to pop up in the right-hand corner when you unzip the file you can grab all of these images you'll notice how each image asset has three different sizes the first one X and then 2x and 3x and this is what we talked about back in our OTO a lesson it's for the different devices having different screen pixel densities so we're gonna just select all of them and then drag them into right here Xcode is going to be smart enough to group all of them in asset names like this these names just pay special attention to them and capitals matter and you can rename them these are the asset names which you are going to refer to these image assets when you want to display them so I just changed the capital B to a lowercase B here to be consistent and yours might already be changed actually so I'm gonna just I'll change that later so when you download it should already be lowercase B the next thing we're gonna do is jump into the storyboard and we're going to start by adding that green background so go ahead and open up your object library you can either click this button up here and just in case you forget or press command shift an L so let's go ahead and search for an image view and drag it onto the view and this is what we're going to do to display images now go ahead and click into this inspector attributes inspector and from the image property let's choose background now we're going to stretch this out to all of the edges of the screen make sure you have that background highlighted and then click this at new constraints button and we're going to want to uncheck constraint to margins because we want it to reach to the edges of the screen ignoring margins so leave that unchecked or actually actively unchecked out because by default it is on the other thing you want to do is pull down all these little dropdowns and choose view instead of the safe area because we want to specify a margin that is relative to the view rather than the safe area and in just in case we didn't go through what the safe area is if you go into the document outline right here and you click on the safe area it's just that blue highlighted area is the safe area and it's a place that's guaranteed to not be obscured by anything so for example the iPhone 1010 are 10s and those ones they have a notch at the top right and so the safe area is actually below the notch so anything that you put in the safe area is guaranteed not to be blocked by elements like that and especially if you can flip the orientation so that notch could be at the bottom or it could be you know on besides the safe area will guarantee that it won't get obscured by that knowledge anyways going back to our background image make sure you have it highlighted again click on this menu we're gonna have to start over so uncheck it constraint margins and then choose view for all of these guys before you change the numbers in here I would pull up down this drop-down and change it to view first and then go back and edit all the numbers to zero making sure that all of these red margins are enabled it's going to say add four constraints down here the reason why I want to toggle this to view first before changing the value here is because when you choose a new option in this drop-down it automatically changes that number in the text box so you know if you did it the other way around you would have to basically change the numbers again so that was just to demonstrate let me just double check that all of them are still set to view okay let's set these to zero add four constraints and you should see your background stretched to all four edges now if you somehow didn't your background isn't looking like mine then you can always just open up this constraints you can delete all of them and you can try again no big deal next thing we're going to do is add another image view so again open your object library drag an image view onto the view this time we're gonna choose logo and ignore the fact that it's big and fuzzy or whatever right now we're gonna add some constraints to it first so let's horizontally center that in the container it's gonna look squished that's okay for now and we are going to add a top margin and we are going to leave it relative to the safe area and we're gonna leave constraint to margins enabled because we don't want this logo to be obscured so we want to just make sure it's in the safe area when you add that the image view is going to use the intrinsic size of the image which is just the size of your graphic asset and so it's going to look like that the next thing we want to do is we want to add a stack view so we learned about these in the previous lesson we're gonna choose a horizontal stack view and this horizontal stack view it's just going to contain the two card elements so go ahead open up the object library again and choose image view now we're gonna put this in our view but we can either drag it into the stack view on the view or we can drag it into the document outline and because the stack view is invisible like this I usually find it easier to put it into the document outline and that's what I'm going to do here I'm gonna drag it here I'm just gonna show you what a potential mistake is now if you drag the image view and you try and put it inside your stack view and it's at the same kind of hierarchy level right here as the stack view that's not what you want you want the image view to be inside the stack view so let me show you what that looks like let me move this image and let me just drag it into the stack view now you can see this little collapsible triangle appear beside the stack view that means I can close it and open it and when I close it the image view is inside the stack view so that's what you actually want we're going to add a second image view into the stack view so we have two and then you're gonna click on the first image view and you're gonna choose a card so let's just say card six and you're gonna click on the second image view and you're gonna choose doesn't really matter let's choose 10 and now let's add some space in between the two cards so we're gonna go on the stack view here and we're gonna choose spacing 30 just to give it some space now before we align the stack view onto the screen I want to put this horizontal stack view into a vertical stack view along with a button so we're gonna add the button first let's drag this button down here and let's configure this a little button a bit for the image property of the button why don't we choose deal button and actually I want to make one little distinction here you can choose background or you can choose image there's a slight difference so for the image property it's going to put that image beside the button text but if you choose background that image is going to appear behind the button text so that's what that distinction is alright so now we have our deal button and we have the two cards here I'm going to put both of all of these elements into a vertical stack view so I want you to go into the document line highlight your stack view hold down shift on your keyboard and click on your button as well and that's going to highlight both of them and I want you to come down here and choose embed in stack view what that's going to do is immediately take those elements that you've highlighted and put them into a stack view now it's Xcode is gonna be smart enough to take a look at how your elements are oriented and it's going to see that our horizontal stack view is above our deal button so it's automatically going to put these two things into a vertical stack view check this out stack view boom vertical stack view you can see this in the document outline alright the other thing it does is it tries to set some of the properties of the stack view based on how you laid out the elements so for example here it's at the alignment the center the distribution to fill and the spacing to 46 because that was the amount of space we had between the horizontal stack view containing the cards and the deal button now I'm gonna change that a little bit I'm gonna say I wanted 30 instead of 46 and now let me rename this in the document outline because as soon as you're gonna have more and more elements and you're gonna have a ton of stack views or a ton of image views things can get confusing so you might have noticed for these UI image views when we've set the image property of it it automatically changes the name of that image view in the document outline so that's helpful but for the stack views they're all just gonna say stack views so for this one I'm going to say cards yeah you can you can name it anything you want let's say cards and the button stack view right for this one maybe cards stack view okay and for the button you can name these two okay so now let's collapse this and let's position this stack view onto the screen so make sure it's highlighted we're going to choose horizontally centered container as well as vertically and that's going to effectively Center the whole thing onto the screen now I'm going to make a slight adjustment here I am going to go into the size inspector while I have this stack view highlighted and I'm going to take a look at the two constraints we added I'm gonna double click the center Y constraint and that this constraint is basically putting it in the center of the screen on the y axis I want to move that whole stack view down a little bit because I want to make sure that when you're holding your phone your thumb can reach high enough to hit that deal button so I'm actually gonna change this constant and I'm going to add 20 points to it to bump it down just a little bit so just as a review I want to tell you this Center alignment constraint is basically saying that the center Y of that stack view should equal the center Y of the entire view plus 20 points that's the what the constant is therefore that's why it gets bumped down a little bit alright so the next thing we want to add are the score labels so why don't we open up our object library again and choose vertical stack view I am going to just put that there in the corner and then I'm going to add a couple of labels I'm going to drag them directly into the document outline into that stack view then it is write two of them so make sure that when you close the stack view the labels tuck inside the stack view all right and now let me edit some properties of this first label and make the color white and I am going to change the text of player and for the second label I am going to change it to zero I'm going to change the color to white and click this guy right here and change the font size to 40 now I'm going to highlight the stack view because we want to position this in the lower left hand corner I'm gonna choose this one the margins and we're gonna make sure that constraint - margins is on and then it's relatively safe area it should be by default right we're going to set the left one to 20 and the bottom one to 20 and this button should say add to constraints and that's just going to position it there there's one more thing I want to do and that is to change the alignment to leading so that's gonna make sure that those elements inside that stack view are left aligned let's change the name of this player for stack view now we're going to do the same thing for the CPU score on the right hand side but this time I'm going to add the labels first just to show you again the two different ways of adding staff views so I'm going to dry two labels here and check this out you can do this you can select both of them remember you hold down shift in order to select click and select both of them and I can change the properties for both of them at once however at this point if I change the text that's going to change it for both of them so let me unselect them and just select the first one and I'll change this at the CPU I'll select the second one and change this to zero and then I'm gonna change the font size as well to 40 and now I'm going to select both of them again by holding down shift and then I'm gonna click embed in and choose a stack view now remember when it when you do this it automatically determines which type of stack view is the best horizontal and vertical and obviously because the elements were on top of each other it shows vertical but it also sets some properties for us which we might not want so make sure you highlight that stack view let's go here see spacing at set 3 so I actually want that to be 0 just like the other player stack view and alignment I actually want it trailing so that it's on the right hand side now let's put some margins on the stack view so make sure you have it highlighted click on this guy make sure constraint amardas it's on by default it should be relative to the safe area which it is let us change 20 and 20 and then down here should say add 2 constraints and there you have it so you have something like this now I want to test this user interface to make sure that it looks decent on all screen sizes and orientations so the way you can do that inside Xcode is down here it says view as iPhone 8 and so far we've been designing this as iPhone 8 in portrait but if you click this open it's got a little tray and yours might actually show the devices if you've got enough space on your Xcode interface if not you're gonna get this sort of drop-down menu like I do so let's first flip this into portrait actually before we do that make sure you press command S and save because Xcode sometimes can crash you know that's not out of the realm of possibility so change orientation let's change it to landscape and take a look so what'd I tell you an internal error has occurred editing functionality may be limited there's not a problem all we need to do is you can come up to product you can clean build folder and this is good learning for you in case this happens for you and then you can just go ahead and quit Xcode press alt Q and you can quit the whole thing and then you can relaunch Xcode and then just reopen your project and that will often time fix things so you can see here's my document outline you can expand that and here is my user interface now sometimes if yours has all these blue squares with question marks on them all you need to do is just go ahead and change the device or change the orientation to force Xcode to kind of refresh things alright so going back to it we have iPhone 8 in landscape it looks pretty good right no problem there and in fact if we go up in size you're just gonna get more space my biggest concern right now is just to make sure that no element is obscured or hidden or blocked or clipped or anything like that and that the user interface doesn't appear broken it's okay if you have extra space you know you can in the future take advantage of that extra space somehow but what you really want to avoid is to have your elements kind of like overlapping each other in the case that there isn't enough space so instead of going up I'm just gonna check the sizes going down because I know as it's gonna get to the smaller phone sizes things may get clipped so why don't we try portrait first let's just jump right down to the smallest screen size so still looks good right let's flip it into landscape and there immediately you see that our logo is hidden behind the cards it's probably not what you want even if you think it looks ok I mean you can leave it in my opinion I would want to change that and I'm gonna show you how to change that let's go up one size just to see if the problem still exists and it does so let's go up one more I phone and that one is okay so we need to somehow address the situation for these smaller screen sizes before we can do that I need to tell you about something called size classes size classes are basically categories of screen sizes because there are so many different devices and two orientations for each device that Apple decided to separate all of these into different categories of screen sizes so when you're adding a constraint you're able to say something like add this constraint for all screen sizes as in all categories of screen sizes or only add this constraint for a specific size class so this gives us some flexibility to change the layout depending on a specific size class so let's say your app might look different on the iPad size class versus like a smaller device like an iPhone and each size class is actually defined by two parameters a height and a width now the height can be compact or regular and the width can also be compact irregular so for instance one size class might be compact width and compact height another size class might be compact width but regular height and in the case where you don't care about size classes and you want to add your constraint for all of them it would just be any width and any height now let's dive back into our Xcode project now I can show you how we can add a constraint for a specific size class now the first thing I want to draw your attention to is down here beside the view as iPhone se you can see what size class this device falls under so this is the compact width and compact height the first step of this is just to identify which size classes you have to fix so we identified that iPhone 4s also has this problem and the size class is also compact width in compact height if we go up to iPhone eight the problem doesn't exist but this device still falls under the same size class iPhone 8 plus this one's a different size class because it's regular width and compact height so we what we're going to do in order to fix this overlapping problem is add some specific constraints or variations of constraints to this specific size class so that if the user is using a device the iphone SE or the iphone 4s in the landscape orientation the specific constraints that we add are going to take effect and they're going to correct that layout for them so let me show you how to add constraints to a specific size class so with the size class that you want to add your constraints into choose very four traits and then we want to introduce variations and that's just the specific constraints that I was talking about we want to vary them based on both the width and the height and that's going to target this specific compact width and compact height size class now this section turns blue and it tells you which devices fall under this size class and you can see that it's the iPhone 10s in landscape the iPhone 8 in landscape the iPhone se and landscape in the iPhone 4s and landscape so any specific constraints you add right now to this size class that's going to affect all of these devices in this orientation so just keep that in mind now let's take a look at what sort of constraints we can add in order to correct this layout let's click on the cards and button stat view so the first thing I think that we can do is just to shorten up the space between the button and the two cards so you can see here that by default we have a spacing of 30 but we can click this little plus icon and add a variation based on a specific size class so based on the compact then compact height size class let's add a variation so you can see the WC and the HC sense for the compact width and compact height we're going to say when when we have this size class instead of 30 I want to do 20 and so that's going to fix the problem a little bit but I'm going to add a couple a couple more variations to completely solve the problem I think the next thing we want to do is take a look at this logo and we want to make it a little smaller for these size classes because the logo isn't isn't a functional part so I think I'm okay with making it a little smaller now we don't have any sort of height or width constraints for this logo but what we can do is add a height constraint for the local right now that will only take effect for this compact width and compact height size class and so we're gonna with the image highlighted we're going to open up this add constraints button and we're gonna add a height constraint and you can see right now it has a height of 67 I'm gonna change that to or add a height constraint of 55 and when I add a new constraint now it's going to be only specifically for this size class right here because this part is blue if this part wasn't blue and it was just great then any constraints I add just like we were doing earlier in this lesson applies to any width in any height so it's like all the size classes all right so let me add this height constraint of 55 to the logo and it's only gonna apply for this size class boom all right so this logo looks a little squashed now but we're gonna address that in a second the first thing I want to do is just show you the constraint we added and how you can tell that it's only applying to a specific size class so let's click on this height 55 constraint look on the right-hand side and you can see installed this means it's only applies to the compact width compact height size class and up here it says there is nothing here this is really the any width in any height size class so this is unchecked it's basically telling you that in normal circumstances this constraint is not installed it doesn't exist but on this specific size class it does take affected is installed so that's how you can tell alright so now we're going to address the situation or the problem that this logo is kind of squashed and if you click on it it all goes back down to the content mode and this would be a great chance for me to show you the different content modes so let me first change the background temporarily to blue so you can see kind of where the boundaries of that image view are so by default set the scale to fill as you can see it pulls the image until it fills up that entire image view right let's check out aspect fill now aspect fill will maintain the aspect ratio so it doesn't stretch the image however it's going to start enlarging that image until that image view is completely filled and what that means is that some parts of your image might exist outside of the boundaries of the image view now that might be OK for you and it might not be it really depends on what sort of layout you have another option you can have if you don't want things that are falling out of your image view you can enable clip to bounce and you can see when I click on that parts of the logo just get clipped off right where the boundaries of the image view are and so that's what clip two bounds means but really the setting that I do want here instead is aspect fit right so this is going to maintain the aspect ratio but it's only going to stretch the image to the point where it fills the image view but doesn't exceed its bounds so that I think this is a good way to see the differences between those content modes so I'm choose a SPECT fit I'm gonna choose clear color as the background again alright so here it's starting to look a little better you know things aren't overlapping but if you take a look at the bigger screen sizes let's say this one right here or the 10s there's there's another thing that I want to do I want to bump this down a little bit so I'm gonna choose I'm just gonna go back to the smaller screen sizes first just to make sure that Oh Xcode might be all right so I've got that internal error thing again but it's just something we're gonna have to deal with alright so I'm still varying four traits I'm still gonna move on I think this is fine now I'm gonna select my cards and button stack view I'm going to go into the size inspector and remember we added this the vertical alignment consorted vertical centering constraint and we added a constant of 22 bump it down a little bit well with this ice-class I'm gonna add a variation I'm gonna click this little plus icon for a compact width and compact height size hat classes I'm gonna add a variation and I'm gonna bump it up bump it down even more boom so to me that that looks a little more centered so for these size classes it's gonna do 30 below the center and for other ones it's going to do 20 and then just double check that it looks okay on the other ones so we've got the four s SE the 8 and the 10 so I'm going to click done varying and I think it's gonna look good now you can choose eight you can just double check let's take a look at the 4s let's see still looks good on the smaller screen sizes and when we go into this specific size class' compact within compact height our size class specific constraints and variations are jumping in to save the day now if you're having trouble putting this layout together make sure you grab my Xcode project below and compare it with yours see if you can find any differences and if you're still stuck just leave us a comment and we'll jump right in to help you now in the next lesson we're going to dive right into Swift programming hi and welcome to lesson 5 in this lesson and the next two you're going to be learning the basics of the Swift programming language this is the stuff that you're going to need to know in order to complete the work heart game app as well as our future apps that we're building together now I know that this coding part can seem intimidating at first but I really want you to stick with this really pay attention and I highly recommend that you open up Xcode on your own computer and type out exactly what I'm showing you on the screen by doing that it's really going to reinforce the language structure and the key words that I'm showing you there's really no need to memorize anything at all and I guarantee you by the end of lesson 10 you'll be writing your own Swift code so let's get started so go ahead and start Xcode but we're not going to create a brand new Xcode project instead we're going to create a playground so click it get started with a playground or you can go to file new and choose the new playground as well now you're going to get a screen like this go ahead under iOS choose blank and we're going to save this I'm just gonna save it on my desktop now first let me tell you about what a playground is it's not a full-fledged Xcode app project instead it's just a lightweight file where we can try and test out some things and this is perfect for us because we are going to just be running and testing some Swift code now let me give you a quick tour of the playground and the bare essentials that you need so this big part right here where you're writing the code that's the code editor that's where we're going to be testing out all our code across the top we have the status bar now mine says ready it's ready to run and test some code for you it might be spinning and it might be doing something in the background but when it finally says ready then you're able to run your code now on the right hand side right here we don't see anything what I want you to do is just move your cursor to this line of code at Lane 3 oh that's actually one thing I want to mention first if you don't have line numbers go to Xcode preferences go to text editing and enable line numbers so that's one of the common questions that I get I don't know if in this version of Xcode they've turned it on by default but if they haven't now you know so yeah move your cursor down to the line 3 and you see lines 1 2 & 3 highlighted in blue with this big blue Play icon go ahead and click that what that's going to do is basically run the lines of code up to that point where you click that button so it's going to write run the code lines 1 2 & 3 you're gonna get some sort of output here on this right-hand side this is the preview column and yours might look a little different so I don't want you to focus too much on the output on this preview pane depending on what version of Xcode you have it could look different Oh instead what I want you to do is click in this upper right hand corner and hide or show debug area or the console area and in this lesson we're going to be writing Swift code to put things into the console area so I want to focus on the output in the console area here at the bottom rather than the output on the right-hand side here in the preview because that could look different for you all right now let's take a look at the code in here before I explain to you what these import VAR keywords are I want to talk about comments now if you've programmed before in another programming language then you'll know what these are but if you're completely brand-new to coding then I think this is a very important part to start off with so let me show you what a comment looks like I'm going to hit enter to start a new line and I'm going to add it to forward slashes like that and then I can type a note for myself this is a comment now mine looks like this grayed out text right here depending on what sort of color scheme you have going on this could be green and can be another color that's not the important part the important part is that anything after these two forward slashes this is not going to be run as code instead it's going to be treated like a note or a remark for yourself too and you can write anything in your comment to remind yourself maybe why you wrote that piece of code or what that piece of code does when you're working with a team of people it's crucial that you leave comments in your code so that when your teammates see your code they understand your reasoning behind it and they understand why you wrote it now if you're working by yourself that's also important to leave yourself comments because if you leave your project and you come back months later you won't remember why you wrote that code unless you leave yourself comments to remind yourself all right so let's talk about this first line of code where it says import UIKit now we're going to talk a lot more about UIKit in the future but for now just understand that uikit is a library of code that apple provides for us to build apps with it it contains useful elements like buttons and labels and templates of code that we can use to speed up our app development import is a special keyword to say that we want to use the uikit library in this file now let's talk about line for this VAR str equals hello playground in order to understand this we need to first talk about variables in an app there's a lot of data being passed around and you need a way to keep track of it well that's what a variable is for you can think of a variable as kind of like a sticky tab you know those ones where you can write something on it and stick it to a piece of paper to keep track of it well let's take a look at the line of code below which is declaring a new Swift variable and assigning some data to it and see how that compares to using a sticky tab and sticking it on a sheet of paper so var is a special Swift key word that is declaring a new variable using our analogy you can think of this as creating a new sticky tab STR is the name of that Swift variable in the case of our analogy STR is what you write on that sticky now hello playground is the piece of data that we want our variable to keep track of in our analogy that would be the sheet of paper that were intending to stick the sticky tab on and finally the equal sign is us actually assigning that piece of data to that variable in our analogy that would be like sticking the actual sticky tab on the piece of paper now let's go back to our playground and take a look at that line of code again now this line of code makes a lot of sense right we are declaring a new variable STR and we are assigning the piece of data hello playground to that variable now let's consider another scenario using the same analogy of the sticky tab what if we decide to peel off that sticky tab and stick it on another sheet of paper well we can do the same thing with our variable except that there's just one catch imagine that when you were writing the name on that sticky tab STR you wrote it with a permanent marker and so when you peel off that steep tab and stick it on another sheet of paper it's still saying STR on that sheet of paper well we can do the same thing with our variable here we can take our variable STR and we can assign another piece of data to it so let's say another some data and what you can do is use this blue icon here and let's just run our code and you should get some sort of preview there now notice that on line 6 I don't have to write var again because var was just to create that variable in the first place when I use it again I can just refer to it by the name and you might notice that sometimes I say create that's just so that you can understand it a little easier the proper terminology is declaring a variable so now let's write some code to output some of this data into the console area below on line 5 here let's write the keyword print and you might notice that Xcode pops up this little autocomplete menu and that's just X code trying to guess what you're trying to tie and presenting you a bunch of options to make your life easier now while you can select some of these options that's not what we're going to do right now I'm going to open up a round bracket and we are going to type STR and if you don't have a closing round bracket you should just type it what we're gonna do now is just bring your cursor down here to line seven or at the end of your code file and click run and you should see hello playground down there below now notice that it doesn't say some data and that's because we are printing out the contents of STR at line five we're going to write after we assigned hello playground so it's showing you the data that STR is pointing to at that point now if we ran another print statement here let's click run you'll see this print out again but this time it says some data which is what we assigned it to it on line six now the next thing we're going to talk about are constants constants are like variables except that once you assign some data to a constant that's it you're not going to be able to assign anything else to that constant now using our analogy that is like super gluing that tab to that sheet of paper there's no way you're going to get that tab off its bookmark to that sheet of paper and that's the piece of paper it's going to reference forever the syntax for declaring a new constant kind of looks like what we did with a variable except that we use the let keyword instead of the VAR keyword now let's go back to our playground and we'll try it out now let's try declaring a constant at the bottom of our playground let's say let STR equals more data and give it a sec or you might have to run your playground but when you do you're going to get an error and it's basically saying that you cannot use STR again because your variables and constants must have unique names even between two variables or between two constants you have to have unique names so why don't we change Esther to Khan and it has to have unique names just out on a side note because otherwise it would be very very good using so we have gone here and let's try modifying metadata for that constant and give it a sec and Xcode is going to tell you that you cannot assign another value to constant or con because let is a constant so you can actually do this but with variables we can write this goes back to us saying that constants once you assign a piece of data to it that's it so now you might be wondering when would you use a constant versus a variable well the general rule of thumb is that you should be using constants whenever you can but however if you're keeping track of a piece of data that you expect might change then you would use a variable because a constant is a lot safer right once you assign a piece of data you can be guaranteed that that's not going to change on you so in fact even inside of Xcode when you're programming if Xcode notices that you use a variable and you assign a piece of data to it and you never reassign anything else to it and it doesn't change it's going to say hey why don't you change this into a constant you're gonna get that reminder so the general rule of thumb again is to use constants and if you realize that that piece of data needs to change then you can change that constant to a variable by just changing that let keyword to a bar keyword alright so let's see erase this line here now one other thing I want to point out and you might have noticed this is that all of the data that we've been assigning to our constants and variables thus far have just been this text data well there are actually other types of data as well and that brings us to our next topic which is data types the pieces of text that we've been assigning to our variables and constants are called strings now I know that's kind of a strange name but you can think of it as a string of characters right well they're just basically pieces of text next up we have boolean or bool for short and these represent true or false great for pieces of data that can only be one of values now don't worry we're gonna try all of this out in the playground in just a second but next up we have integers or int for short just like back in math class integers represent the whole numbers in the positive to the negative range including 0 now you might ask where are our decimal numbers don't worry I've got you covered float is what you're looking for and these represent our floating-point data in other words our decimals I've just showed you for data types but there are actually more but these four are great to start with I have a swift cheat sheet at the end which are going to show you the rest and also a worksheet for you to practice what we've learned in this lesson now let's go back to our playground and try this stuff out all right so now let's try some of those data types that we just talked about let's type in bar b equals true and let's print B now let's try running this line of code here and you're gonna see true appear down into console below now true is a special keyword that you can use to specify a boolean value we can also change this to false let's run this again and you can see false appears on the console now that we're running more code I want to point your attention to a special feature of the playground and down here in this stop playground button you can actually hold it and choose automatically run when you do that your playground is automatically going to execute the code in your playground automatically as you're typing so you never have to click on that Run button again the only problem is that sometimes the playgrounds can be buggy so if you're experiencing a lot of crashing or it's not running your code then you're gonna want to switch back to manually run and you're going to want to click on that run code button manually so we're gonna leave it automatic for now and see how how it goes if we are experiencing problems with our playground then we're going to set it to manually run instead all right so now let's try out integers let's do var I equals 32 that is going to declare a new integer and assign it 32 we're gonna assign a 0 that's also an integer I'm gonna try assigning let's say negative 10 it's also an integer now let's try the last data that we talked about which is flow and it's gonna be some sort of decimal number like that now there's one important thing I want to talk to you about and that is that there are actually two types of decimal numbers so the first decimal number data type is float like we talked about but there's also something called double and it's another data type that represents decimals and in fact double is a lot more precise than float that means that a double data type can store a lot more decimal points than a float data type can and when you're working with the Swift programming language double is actually the default a data type now the thing is it's important to know both float and double because sometimes when you're working with third-party code libraries or even some of the libraries inside UIKit some of them expect float data types and some of them expect double data types and so it's important to know both and how you know now the next thing I want to talk to you about is the fact that variables and constants can only store one data type now what do I mean by that I'm gonna demonstrate so here we've declared a variable called I and we've assigned it an integer and then we've reassigned it 0 and negative 10 which are also integers but what if suddenly I decide to assign it some sort of decimal number right we know that decimal numbers is that's not considered an integer so in fact right here the playground is telling us it's erroring out and it's saying that you cannot assign a type of double to your integer variable you just can't do that because the variable I only accepts integers now here's the thing we're did we say that variable I can only accept integer data types well the funny thing is that we didn't explicitly say that what happens is that when you declare a variable or constant and you assign a piece of data to it that first piece of data is it's going to take that data type and infer that that's the data type that variable can store and that's the only thing it can store so the very fact that we assigned 32 being an integer to variable I from that point on variable I can only store integer types that is why we cannot we cannot assign this double data type value to I same thing goes for this up here because we assigned the boolean value false to be now the variable B can only store boolean types so I can I can assign true to it but I cannot assign piece of string to it I cannot assign a number to B and so we're gonna get these errors right here all right so we've just the experience at crash on the playground okay let's just go back to manually run and we run our code right here and that should be okay all right so we're back to being good now there is a way to explicitly say that a variable can store a certain data type this is how we would do it so after your variable name you would write a colon and then you would write in the data type that you want that variable to store so you can write like that you could do that up here you could do that and then for this one you can either type float or use the swift default double so I would recommend using double when you can unless you're using some sort of library that requires you to use some float data so here's the funny thing even if this is the first piece of data you have sign being float simply because you declared your variable as an integer you know you've explicitly said that variable I is an integer data type you cannot assign a double data type to it so those are the things that I wanted to point out to you I know it's a lot to absorb I would recommend getting the recap notes and just reviewing it and also doing the exercises it's going to help you solidify these things in your head so far you've learned about variables and constants and how they can be used to store data you've also learned about data types such as in string boolean and float now all of this is going to be in the Swift cheat sheet which you can grab below as well as the stuff for the next two Swift lessons I also have a worksheet for you to try to practice using swift variables and how to perform math operations on them so make sure you try that and get some extra practice in hi and welcome to lesson six in the previous lesson you'll learn how to write some basic Swift code well let me ask you something how does a user usually interact with an app well it's usually they tap on something on the screen let's say a news headline and then the app gives a reaction such as showing that news article action and reaction well that implies that when the user takes an action depending on what that action is the app needs to react accordingly and run the appropriate block of code depending on what the user is doing so we need a way to organize our code into bite-sized chunks so that when the user takes this action we run that chunk of code and when the user takes that action we run that chunk of code well Swift has something called a function and this is basically a block of code where you wrap it up with a name and when you want to run that block of code you can just call it by its name so let's open up a new Xcode playground and see how we can declare some functions all right so we're gonna create a brand new playground here and we're gonna try out these functions so let's get started with a playground under iOS let's choose blank and I'm just gonna save it on my desktop and call it my playground - all right so we're gonna just go down here create a new line and we're gonna type in f U and C space now that keyword is used to declare a new function next part of the function is the name of the function now this is important because whenever we want to run the code that is inside this function we're going to call it by this name that we're gonna give it right now so I'm gonna call this function say hello now the next part of the function is a pair of rounded brackets so find that on your keyboard typically it's right above the nine and the zero so you're gonna have to hold down shift and you know type those two rounded brackets now inside those rounded brackets right now we're not going to put anything in there but you can have something called parameters which is something you're gonna learn a little later in this lesson alright now next we're gonna hit space and we're gonna open up a pair of curly brackets or squiggly brackets some people call them and you got to find these on your keyboard - for my keyboard layout it's above the square brackets so I'm gonna hold down shift and type in a pair of squiggly brackets or curly brackets I'm go inside it and press ENTER a couple of times to create a few lines you're going to write your code for your function in between these two curly brackets think of it as the guts of the function so whenever you call say hello the code in between these curly brackets it's going to get run I'm gonna print out in here hello all right now let's go outside of the function and by outside I mean after this ending curly bracket we're gonna just call the function by its name say hello and notice that autocomplete already brings this up but let's type it out just for extra practice so we're gonna use the name of the function followed by the curly brackets all right now let's run this line of code you'll see down here it's going to execute this print statement and it's going to print out hello and if you don't have this tray at the bottom you can open it up like that when you write a function you're usually writing some code to perform a specific task in our example before you wrote a function to display the full article and when the user taps on a news headline in the app you're going to call that function to display the full article for that headline now let me present another scenario what if there are 10 news headlines in your news app are you going to write 10 different functions one to display the full article for each headline of course not furthermore the news changes every day so you wouldn't be able to write a function to show a news article that hasn't happened yet right instead you're writing a function to do the work to present and display a full article to the user that function doesn't care or doesn't know about what sort of article it's going to be presenting and displaying you as the coder basically pass that information into the function when you call that function you can do this with something called function parameters remember those rounded brackets in the function call well you can specify the parameters in between those rounded brackets that indicate what sort of data you're passing into the function when you're calling it in the example below we declared a function called say hello to in the rounded brackets you have a parameter called name and it's of the data type string now that kind of looks like a variable declaration without the VAR keyword whenever you call to say hello to function you're going to have to supply a piece of string data into that function call now let's jump back into our playground and see this in action alright before we jump into an example with parameters let's first add a comment up here and call this a basic function remember this is something you should get into the habit of doing and I also want to show you if it wasn't clear how to use the autocomplete feature because trust me you're going to be using it a lot so why don't I type say hello you're gonna notice that it pops up right here now you can either hit enter right now or you can press up and down on your keyboard to select a different one and you can even use your mouse and you can scroll down the list and so here I'm just gonna double click it alright so now let's do a function with parameters so again we're going to type in a few and see space for declaring a new function and this time I'm gonna call it say hello to and we're going to specify the rounded brackets just like before except that this time I'm going to move my cursor inside the rounded brackets and we're gonna put a single parameter in here let's call this parameter name : we're going to specify the data type it's just like almost the like declaring a variable like we did in the previous lesson alright so now we're gonna open up a pair of curly brackets and we're gonna add some space in there and here we are going to print out the name that gets passed in and the way you can do that is just by referencing that parameter name so we since we called it name we can just say print name so what ever data gets passed into this function when it gets called we are going to be printing it out into the console so right now even if we run the code it's not going to do anything we actually have to call the function so here below the function let's type in sa Y and you can see that now autocomplete shows you the second function that we just wrote so go ahead and select that and press Enter and this highlighted blue part is telling you that you need to specify a piece of string data along with this function call so why don't we go ahead and I've been Tom there and then let's run this line of code at this point so you're gonna see Tom there right and that's just a result of us passing this piece of data into the say hello to function so that's going to come in through here and then it's going to take that string data and print it out to the console and that's why we get this result down here now what if we wanted to say hello Tom instead well we can't do that and I'm going to show you a really neat way to do that so let's erase this name here and instead let's print out a string called hello space and we can actually insert that name parameter into the string and the way you do that is backslash and then type in a pair of rounded brackets and inside the pair of rounded brackets you would just put the name of your parameter or variable or whatever you want to insert into the string now let's run this function call again now you get hello Tong now in this example we've done one parameter you can actually include multiple parameters into your function all you would have to do is inside the rounded bracket after the first parameter just I've been comma and now you can require a second parameter so let's make this one age and this datatype for the age is going to be an integer so immediately the playground is going to complain that this function call is no longer valid and it's right it's missing an argument it's missing this parameter called H so what I'm going to do is just completely get rid of this line and going to type in s a Y and you can see here that autocomplete has detected we've changed that function so the double click it or press Enter and we're going to fill in the parameters that are needed now here's the neat trick as you're filling in the parameters here if you press tab on your keyboard it just automatically jumps to the next parameter that you need to fill in so that's a shortcut that's going to help you so let's type in something like 20 years old and let's run this code now again it just says hello Tom because we haven't included the H parameter in this print statement so why don't we modify this piece of text you are backslash rounded brackets let's insert that age years old and now let's run this function again and now you're going to see down here hello Tom you're 20 years old now you can actually specify more parameters but I wouldn't go to too crazy with this in the future as going to get more advanced with Swift are gonna learn ways to combine pieces of data together into one parameter and so you don't have a long long parameter list that you're gonna require but for now if you wanted to include you know two three four five parameters just to play around feel free to do so it's going to be good practice there's one thing that I want to mention and that is that you can actually omit these parameter names right here so it's going to I guess save you a little bit of typing sometimes it can be nice to have them so that it's really clear what sort of data you need to pass in but let me show you how you could do a function call where you can omit this all you would need to do is back in your function declaration here you would just include an underscore space in front of that parameter so we're gonna do the same thing with the age here and then we're going to get rid of this line in fact Xcode is now or a playground is now telling you that you don't need these things so let's get rid of this line and again use autocomplete and you can see there's our function visually here it doesn't look any different but if you press ENTER you can see that this whole thing is highlighted now and when you add your parameters right it's just gonna look like that for your function call so when you're actually doing here by adding this underscore is you're omitting something called the argument label now I'm not gonna get too much into it right now because I don't want to confuse you with a lot of knowledge that you don't need right now but just know that that's something that you can do I will link to some resources in the description if you want to read more into it but if even if you don't as you're going to get a little more advanced with Swift and you're gonna learn more about functions you will come across this knowledge anyways so it's not nothing to nothing that you need right at this moment now you know how to write functions which expect some sort of input data to work with another great use of functions is to take that input data process it and transform it and then return it back to us now functions can do this using the return keyword in the function below it takes an integer input it adds 4 to it and then it returns the result back to us now notice that after the rounded brackets there's an arrow followed by the data type int now this describes the type of data that the function will return when you call it now let's go back to our playground and we'll try this out all right so now let's try out a function with the return value so why don't we just type in a new comment here with return value and I'm going to create a new function by typing f UNC space and then I'm going to call this function add four two and you guess that we're going to add a parameter in here I'm going to call the parameter X and it's going to be an int data type and here is where we get to the return value part so we're gonna type in a - a greater than sign space and here we indicate the data type of the value that is going to get returned by this function so since we are simply taking it in an integer and we're going to add 4 to it it makes sense that what we're returning out of this function is also an integer so that's what we type in there and then we are going to hit space and write in our curly brackets there now I'm gonna open up the curly brackets a little bit so we can type some code in between them and what we're going to do here is we're gonna create a brand new variable here let's just call this sum and the sum is going to be equal to X which is the value that gets passed in that integer and we're going to add 4 to it now from here you can see that the playground is complaining that we're missing the return in a function that is expected to return in in data type and it's right because we need to return this sum the keyword that we use is actually just to return so type in return space and we are going to pass back the sum so if you let let Xcode run or maybe you can run your code at this point you're gonna get rid of that error so let's try this out let's try calling this function ad d4 and autocomplete brings it up let's hit enter here we're gonna pass in let's say 10 let's go ahead and run this function at this point we don't really see anything I mean you see some you see the result in the preview here but like I said we're gonna pay attention to the console nothing gets output here well where did that 14 go right what's actually happening here is it's passing in 10 into this function right through this parameter then it's adding 4 and then it's returning the sum and we are actually responsible for capturing that data so in fact what we have to do here is we have to type in var let's say result equals the execution or the return result by executing this function so if we print the result and we run this code we're gonna see 14 down there in the console so just to run it through one more time what's happening here is we're executing this function we're passing in 10th as a parameter then this code inside this function gets run right it's gonna take 10 which we passed in it's gonna add 4 to it it's gonna assign it to the variable sum and then it's going to return the the data sum right and that's going to come back here and that sum gets assigned to result and we're printing the result now one question you might be asking yourself now is why do I have to use return values why do I have to use this return keyword here why can't I just access some right here why can't I just say print sum so why don't you go ahead and try and run your code and you're gonna get an error that says use of unresolved identifiers some and if you scroll up here that's the same error message but it's basically saying that it cannot find anything called some well what do you mean we have some declared right here inside this function this brings me to my next topic which is variable scope you see the code that is inside this function right here is inside of its own scope so any variables you declare in here only exist within that function and that's why in order to get that data out you have to use the return keyword what I find helps beginners to grasp this concept is by thinking of the code inside of the function as existing in its own little bubble so anything that you know the code that you write here the variables that you declare inside that function is in its own little bubble and in order to get that data out you're going to use the return statement here now another thing I might add is that each function has its own scope or its own bubble so if I let's say declared another function let's just call this C and I you know I try to print some in here I'm also going to get an error right because some exists in this functions scope I can't access it anywhere else each function has its own variable scope now I know this variable scope concept is a little bit abstract but what's going to happen is that as you're writing more Swift code and you're building your apps you're gonna run into issues where you're trying to access this variable inside this scope and then you realize that you can't and it's just something over time that you're going to realize and it's gonna click if it hasn't already clicked for you so I guess what I'm saying is that give it some time and don't worry if it's kind of confusing to you right now what I'm saying is that as you writing more code and you're building raps you're writing more functions these things are gonna fall into place for you so let's erase that test function and let's address this thing it's so annoying this variable sum was never mutated consider changing to a let constant so this goes back to what we talked about in the previous lesson when should you use variables and when should you use constants well I told you that you should default to using constants and then if you find out that you need to change up that data and you get an error to say that you can't change it up then you can consider changing that led to a var and using a variable instead so here Xcode is warning you that hey you know you declared some as a variable but in fact after you've assigned some data to it you never ended up changing it so why not use a constant and so Xcode is being very helpful not annoying in fact let's change that to a let and we're all good now Before we jump to the next lesson one last thing about autocomplete so I want you to notice when we typed in add four to this right here this is the return value so when you're looking through different functions to call this is very handy to understand what sort of data this function returns what happens if we try to now call one of these guys say hello to or say hello in fact these guys they don't have return values right so what happens when we try to autocomplete that well it says void well void basically means no return value so that's what it means and why why does void say that because in fact let's go back to the basic function here in fact right here the return value is actually void it's just that we don't have to type it when it's void so you can actually specify a return value of void which is basically no return value and you don't need a return keyword so that's just a neat little fat when you don't need a return value you don't need to specify this part of the function declaration you can kind of omit it but the interesting part is when you use autocomplete to call this function it still says that the return value is void all right so today you learned about how to organize code into functions you've learned about input parameters which let you supply functions with input data you've also learned about return values which let functions return data back to us and finally you've learned about variable scope which is basically all of the variables and code inside of a function only exists within the scope of that function believe it or not there's still a lot more to functions but what we've covered so far is more than sufficient for now I've got two worksheet for you to practice it and solidify what you have learned so make sure you grab that and I highly recommend that you go through it hi and welcome to lesson 7 so far you've learned some basic Swift code and how to organize that code into executable blocks called the functions well in this video you're going to learn how to organize and group your functions into what's known as classes now before we go on I just want to say one thing and that is that learning something new is hard seriously I know firsthand because I fail that learning iOS programming when I first started so give yourself a pat on the back for coming this far especially if you've never coded before now I know you might be asking yourself constants variables functions why the heck do I need to know any of this well I can guarantee you that after this lesson and into the next all the pieces are going to start to fall into place for you because we're going to move back to our Xcode project and I'm going to point out all the different pieces that you've been learning about in the last three lessons and you're going to have a Eureka moment you're going to see that Xcode project in a different light so I want you to pay extra careful attention in this lesson because it's the last one before we move back to our work hard game Xcode project all right let's do this so on the screen I've got two functions right now they don't really do anything but one is called cruise and one is called thrust so let me explain why imagine yourself as an engineer for NASA and you're writing the code to power one of their rockets now all of the code for cruising you would put inside the crease function and all of the code that are going to turn on the rocket thrusters you're going to put it inside the thrust function now just like how you organized that code into those functions you can further organize these two functions into a class because potentially you could have many many functions right so a class you can use it to group together functions that kind of serve the same purpose or the same goal so let me show you how to declare a class first of all use the class keyword and then you would give the class a name so I'm gonna call this rocket now I'm gonna call it spaceship just because I like that word a little more now you open up a pair of curly brackets and I am going to put some space inside the curly brackets and I'm going to highlight these two functions and press command X to cut them and I'm going to press command V and they're to paste it so what we have now is kind of like three levels of organization right at the top level we have this spaceship class inside the spaceship class we have two functions cruise and thrust and inside each of those functions we have the code to essentially carry out those abilities now there's one distinction I want to make and that is that when you move the function into a class those functions are now called a method of that class so I know it's a little confusing because nothing's changed except what you call them all right when when there's a standalone thing they're called functions but when you put these functions inside a class they are now called methods of that class but it's sort of interchangeable if you say you know the crues function of the spaceship class people will still understand what you're saying but I just want you to know that the correct terminology is that Cruise is a method of spaceship all right just a little distinction there let's illustrate this in the diagram first we had functions and then we put them inside of a class and now they're called methods I want to talk about variable scope for a second in the last lesson you learned that declaring a variable inside of a function it only exists within that functions scope so for instance if we declared a variable called name in function a we can't access that named variable in function beat because function B has its own scope the same goes for the reverse if we declare a variable in function B we can't access it in function a because that variable would only exist in function B's scope now get this the class itself has its own class scope you can actually declare a variable inside class but sits outside of any particular function now this variable exists inside the entire scope of this class since function a and function B are also inside the scope of this class they can actually access that variable finally here's the kicker when you declare a variable inside the class but it's outside of any functions like what we've done here it's actually called a property of that class now let's see this in action so let's go ahead and declare a property of our spaceship here now it's going to be inside of the class right that's the starting curly bracket but it's going to be outside of any of these two functions so I'm gonna put it up here I'm going to call it a fuel level and I'm going to assign a hundred to it now this fuel level property is inside the scope of the class just like how these two functions are also inside the scope of the class so I can actually access the fuel level property from here see I can print it out now it's not going to actually print anything because we need to execute these functions and we're going to do that a little later on but just from the fact that actually you know let me run it just to show you that the playground isn't going to throw any sort of errors right so it can access this property however let me declare a variable in here let's just say bar tests is equal to true and make it boolean right this variable because it's declared within the cruise function it only exists inside the scope of that function you know that little bubble so I cannot access it from here let's say print test and you're going to see that Xcode is going to throw an error let's run that so it's saying that it cannot find test because it only exists within this scope so now let's go ahead and erase this test code here and like I said before if this scope thing is a little bit confusing it's going to come with time I promise you that as you're gonna write more code you're gonna understand this stuff a lot more there's gonna come a point where these things finally just like click for you all right now we're going to take a giant leap and I'll explain to you how classes are used now it's going to require a little bit of abstract thinking I also want to add that in my 6 years of teaching iOS app development this is the single hardest concept to understand for beginners who have never coded before but once you understand this then you will have crossed the biggest hump that so many people give up at all right I'm done talking let's do this now let's use the same analogy so we used before suppose we have some data and we have variables and constants as sticky tabs now we have functions that encapsulate these pieces of code and let's say that functions are like file folders now we have classes that contain a bunch of functions and variables and let's say that class is a file box that contains file folders well at the end of the day what we have is just a file box full of instructions it doesn't actually do anything some people say let's think of the class like a recipe some people say let's think of the class like a blueprint what's the common thing here they all need someone or something to turn this set of instructions into action someone to take those recipes and turn it into a cake or someone to take the blueprints and build a rocket ship now this rocket will work exactly like it was designed to it can thrust and it can cruise because we've given it functions to do so but understand that class doesn't thruster cruise it's the actual object that gets created from the class that will thrust their crews furthermore once you have a blueprint you can make multiple spaceships each of them will have its own fuel level and ability to thrust their crews the blueprint is called a class and the object that are created are called objects or instances of the spaceship class all right so who is the person that will take that class and turn it into an object well that's the device in your hand it's a mini computer you write your instructions in Xcode Xcode will turn it into a format that can be understood by your device and your device carries out those instructions so here's the tricky part you need to write instructions to tell the computer to take your classes and to turn them into objects and furthermore you need to write instructions to tell the computer how you want it to use those objects for example you write instructions like when the user taps the lift off button then you create an object from the spaceship class then call the thrust function of that object then called a cruise function of that object you know that could be an app right there now let's go back to our playground and see how you can write instructions like this all right so you just learned that a class with its properties and methods they don't actually do anything until you bring it to life by turning it into an object or an instance of that class so essentially when you're writing this code and organizing your code into functions and organizing your functions into classes you're really designing something right you're programming something to be turned into an object to be used so before we create a spaceship object from this class I want to first add another property and some code to the cruise and thrust functions so that they actually do something so up here right below this property I'm going to declare another name property and I'm going to assign it an empty string so you can actually do that it's a string but with nothing inside but essentially it sets the datatype for this name property and inside the cruise function here essentially I want to print out a statement but I want to include the name so I'm gonna say cruising is initiated for and then I'm going to insert the name remember how we do this you learn about this a couple lessons ago I believe or last lesson backslash and then rounded brackets and you put in the variable name and it's gonna insert that into the string so we're gonna do thrust this well so we're gonna say is let's say rocket thrusters initiated for name alright so now we can bring this spaceship class to life by creating a spaceship object from it or in other words an instance of the spaceship class and the way we do that is we basically type in the name of the class followed by two rounded brackets so let's start doing that and you'll notice that autocomplete shows us you just press ENTER and then you can go ahead and put two rounded brackets like that now that kind of looks like a function call right and just like a function call with a return value how it returns something too and you need to capture it using a variable or a constant the same thing is happening right here by writing this line of code you're creating a new spaceship object and it's being returned to you so you need to keep track of that data using a constant or a variable you know use a variable because I want to show you how we're gonna try assigning something else to this variable all right anyways I'm gonna call it my ship and it's going to keep track of that spaceship object that we just created I want to show you something interesting why don't we try assigning another type of data to my ship for example in integer 10 well you'll see that we can't assign an integer to this variable because this variable is of the data type spaceship well what do you mean we went through some data types in lesson 5 remember string bull in float double well as it turns out when you create a new class this is now a custom data type so spaceship is actually a data type so what you've done here with this line is that you've said my ship is a variable that can only keep track of data that is of the spaceship data type so essentially that's what's really happening here you're declaring a my ship variable that is going to keep track of spaceship datatype and you're assigning a new object to this variable so I just wanted you to know that so that it doesn't get confusing otherwise now the next thing I want to show you is how do we access the properties and methods of the newly created spaceship object well we have a reference to that newly created spaceship object from this variable my ship and if you've never heard of that terminology before a reference is essentially what your variable or constant is it's keeping a reference or keeping track of a piece of data which in this case is the spaceship object so my ship is a reference to that spaceship object all right so all we do is we type in your variable name or your constant name or you know whatever has the reference to that object press dot and this is called dot notation this is how we are going to access the methods and properties of that object as you can see autocomplete pops at this menu and we can you know we can access the name the fuel level the cruise and the thrust functions and you know when you get more advanced with Swift there are actually ways to restrict what can be accessed but that's for the for later for the future for now I want to set its name so I'm gonna call I'm gonna access the name property and I can actually say that this name property should keep track of a new piece of data I'm going to call this ship Tom all right so I'm assigning the string Tom to the property name for that object my ship and next I'm going to call using dot notation the cruise function and when I run this code you can see cruising is initiated for Tom but had I not set this line remember I'm going to use a comment here we talked about comments in lesson 5 that essentially turns this line of code off and treats it as a note or a remark so I'm going to turn that line off and then I'm going to run the code again and you can see cruising is initiated for empty string nothing ok so that's kind of cool we could also call my ship daunt thrust and we could run that and you can see there it goes I can also just access the properties I don't have to be assigning things to it so for example let's erase these two lines and let's say let's print out my ship dot name and let's print out my ship dot fuel level so let's run that you can see it's Tom and 100 I like to think that coding an app is like writing a script for a movie the movie script is your app code the character roles are the classes that you've designed but character roles themselves don't do anything these roles need to be turned into physical actors and actresses just like we need to turn classes into objects then the actors and actresses follow the script to perform your movie just like how your objects work together to make your app function so all of this stuff is pretty abstract but in the next lesson we're going to put it into practice but first let's do a quick recap of what we learned in this lesson because it was quite a bit now classes contain methods and properties and remember methods are just another name for functions you also learn that classes by themselves don't do anything they need to be turned into objects first these objects are also referred to as instances of that class so remember a classes kind of like a blueprint and the object is what's created from that blueprint you learn how to create a new instance of a class and you also learn about dot notation which is used to access the methods and properties of that object now if you need to I recommend to re-watch this video and ask any questions you have in the discussion area below I also have a worksheet for you to practice and to solidify these concepts in your head and if things are still a little fuzzy and it's completely normal if they are I highly recommend for you to download this worksheet and go through it now in the next lesson we're going to use your newly minted Swift skills to bring the war card game to life now if you're excited about that like I am I've been done pumped into the discussion area below hi and welcome to lesson 8 you're almost there only two more lessons after this one and in this video we're going to return back to our card game Xcode project and I'll explain to you how those Swift Basics you've learned apply to this project by the end of this lesson you'll know how to write code inside the view controller to access and manage those elements that we've created in the storyboard I'll also show you what to do when your app crashes which is something that actually happens quite often into all of us so if you're ready let's do this so here I have our war card game Xcode project and we're going to jump right into the view controller dot Swift file now that you've gone through the Swift basics we can talk about some of the code in this file so in this first line import you arcade you know what that means we're basically saying that in this code file we want to use the uikit library that apple provides to make our life easier you go down to this line we have class view controller so right here we're declaring a class called view controller and you can see that it has an opening curly bracket and a closing curly bracket and this inside is a function you can see the F UNC there it's a function called viewdidload now there are some details that we are going to gloss over right now because it's not relevant for what we need right now you don't want to burden you with that information but pieces of information like this here : uiviewcontroller essentially this is something that's called sub classing which is a way for classes to build off of each other so you're not always declaring classes from scratch this is essentially saying that the viewcontroller is building off of another class called UI view controller and this UI view controller class is actually one from UI kit and for this function here you can see that there's an override keyword so you don't need to know about that for now and also this super keyword which again is something that we don't need to know right now but essentially you know at a high level what you're looking at here is a new controller class with a function inside called viewdidload so isn't that really really cool because everything you learned in the last three Swift lessons it you know directly translates to what you're seeing here but as you learned in the last lesson the view controller class by itself is just a blueprint it doesn't do anything right you need to turn it into an object first so now we're going to jump into the main dot storyboard and take a look at the work that we've done here so all of these elements that we've added into the view here and that we've configured what are they are the objects are they classes well believe it or not what we've been doing here we've been creating objects and you might say that hey Chris from what I've learned objects are created from classes right but what sort of classes are these guys objects of well let's take a look at this object library here you see all of these things these are classes inside the uikit library yes that library that we import all of these useful classes like buttons text fields and sliders and stuff like that when we drag one of these elements on to the view we are actually creating an object of that slider class or that button class or that uiimageview class and take a load of this when you click on one of those elements or objects now that you know what they actually are and you go here on the right hand side into this inspector you can see all of these things that we can configure well what you're actually doing is you're setting the properties for that object so you see everything maps to exactly what we've been talking about in the last three lessons this whole storyboard is merely a visual way for us to create these objects and set its properties in fact we could just completely omit the storyboard and we can decide to create all of these image objects these button objects through code and then set its properties through code and then put them into the view through code so you completely don't have to touch the storyboard but this is more of an intermediate to advanced technique and I wouldn't recommend that for you right now for beginners I would definitely recommend to start with the storyboard so now that you know that these storyboard elements are actually objects how do we get references to these objects so that we can call their methods and configure their properties through code through the view controller well that's where IBL at properties come in let me show you how we can expose these objects as iboutlet properties so that the view controller can access them now there are several ways to do this but the easiest way is just to go ahead and select view controller here in your document outline and remember that this is the visual representation of the view controller object click this this button here that looks like to Konya circles this is actually called the assistant editor and what that's going to do is split your code editor into two different panes a left side and the right side now I want to make sure on your right side you're looking at the view controller furthermore up here in this breadcrumb sort of navigation I want to make sure that your say automatic here if it doesn't go ahead click it and bring it down from manual or whatever it was set to go under automatic and select view controller and then find this spot here right after the opening curly bracket of the class press enter a couple of times to create some space and on the left hand side we're going to expose this left card this first card as an iboutlet property now you could do it through here the storyboard but what I would actually recommend is to do it through the document outline so go ahead and open up your document outline until you see the card here you know you can select the element it's gonna highlight the different parts make sure you've got that left card highlighted hold down ctrl on your keyboard and then while still holding down ctrl click and drag this blue line should follow your mouse cursor as long as you're holding down the ctrl key now drag it over here you should see this little text that says insert outlet and then you can let go of your mouse button and then ctrl key you're gonna get this little menu here and then you're gonna be able to name this iboutlet property so I'm going to call this the left image view like that and if you've done this with the right element the type should say uiimageview if this doesn't say that for you just click cancel and then try it again the connection type should be outlet and you can go ahead and hit connect and what that's going to do is generate this property for you because you see there's the VAR keyword here is the name of the property here is the data type that this property references which is UI image view and this is special because it's got this iboutlet keyword here which just indicates that this property reference is an object in the storyboard now I'm going to gloss over a couple of things here such as the weak keyword and this exclamation mark here so that's not something that we need to talk about right now but the important thing to note is what you've done here is essentially hooked up that object in the storyboard to this property here inside your view controller so now that you have a reference to that uiimageview object you can call methods on it you can configure its properties inside the view controller here now because often times beginners make mistakes when connecting their first IB outlets I'm gonna go through some troubleshooting steps and also some steps for you to confirm that you've done this properly so go ahead in the document outline for this image that you just connected right click it and it should pop up this little menu and you can see under referencing outlets it says left image view with this view controller here now if yours doesn't say this then you might have connected the wrong element so what I would do is maybe check the stack view you could have accidentally connected this guy right-click it and you know there should be no referencing outlets there you know same thing with the right card view if you click this there should be no referencing outlets if you've by chance accidentally connected another element here's how to fix it go ahead you know when you see that menu here you have to click this little X to break the connection and then go ahead and delete the property and then you just start all over and this time you make sure you have the right element selected hold down control drag that blue line over here let go and then you can say left image view now let's say when I'm typing this out I accidentally make a typo and I connect it a lot of the times beginners will just correct this typo like this and leave it at that but essentially that will cause a problem down the road when you run your app because what happens take a look this right click this and you can see that this image object is connected to a property called left image view with two w's but what we've done here is that we've corrected it so it's gonna look for a property with two WS but it doesn't exist so your app is actually gonna crash that's not the way you want to fix your typos when it comes to connecting Ivy outlets you want to go ahead and break that connection and then just delete the property and you just all over now should show you another way to correct this so the most important part is that you break that connection you can potentially just leave that iboutlet property that was created and then you can right-click your image that you want to connect to that property under referencing outlets click this little circle drag to the view controller let go and it's going to pop up some properties that you can connect this image object to now it's important you don't connect it to the wrong one choose left image view and you can see that this this image right here an image view is connected to the left image view property of our view controller so that's what you want now let's call it connect the right image view hold down control click and drag that blue line I want to make sure that you don't drag it into that same property because if you do that you'll be connecting two elements onto the same iboutlet property and that could cause potential problems so you need to drag it into an empty space where it says insert outlet or outlet kind of collection let go I'm gonna call this the right image of view and we're gonna connect it all right so we've got two we're going to connect a few more let's say we're going to connect the score labels because we're going to need to update them through the code so let's connect this left a player score one and you can see what I did I created a little more space there hold down ctrl click and drag call this the left score label you can see the type now is different it's a different class UI label connect that and then here is the right one right score label all right now I want to show you what an app crash looks like so I'm gonna go ahead and just change the name of my iboutlet property with without breaking the connection and fixing it here in the storyboard and as I told you this is going to cause a crash so let's go ahead and run the project and we'll see what happens all right so right here you see this red highlighted line that's gonna be a crash and we basically see the same thing on the left and right side because we have the assistant editor open but the main thing is that you need to look down here in the console area if you don't have this section just go ahead up here this will show or hide it and on this right-hand side sometimes if you don't have this there are two small little buttons here in the lower right hand corner that let you control the left and right sides so make sure you've got this side here where it shows you all of this text and down here you see terminating with uncaught exception and that's just a generic message for an app crash what you want to do instead is scroll all the way up and that's where you're gonna find an error message which makes a little more sense so here you see at the very top terminating app due to uncaught exception the reason this class is not key value coding compliant for the key rights core label now the line I've highlighted here may not make a lot of sense but what happens is that once you know how to solve this error and the next time you see an error message that looks kind of like this you have an idea about what's wrong and how to fix it in this particular case it's telling you that something is looking for a right score label but it can't find it and we know exactly what the problem is right if we go back into the storyboard write this write the score label you can see if you right click that it says this element is connected to an iboutlet property called write score label spelled correctly but if you look inside our view controller we don't have a property like that we only have this one write score laid without the L at the end and so that's why the app is crashing because it's looking to make that connection that we've told it to make but it can't find you know that corresponding on the outlet so the next time you experience an app crash and maybe you're looking for help online or maybe you're in our support forum and you're asking for help make sure that you scroll all the way up into this console and look for that error message which gives you a hint as to what's wrong if you if you just look at this it's not really gonna tell you any sort of information okay so let's go ahead and fix this by adding that L that was missing and let's take a look that what we've done here so far so essentially let me go back to the single editor view just so you can see a little more clearly essentially what we've done is we've connected the two image view objects from the storyboard and the two labels from the storyboard as well as iboutlet properties here so from this view controller code file we can reference those objects using dot notation we can access the methods of those objects and those properties of those objects as well let me just demonstrate for you so inside the viewdidload method and it create some space and let's access the left image view now hold on a minute why can we access the left image view from within the viewdidload method well this left image view is outside of a function but inside the class so it's inside the scope of the class remember this function is also in the scope of the class so that's why from inside this function we're able to access that left image view property now using dot notation let's click dot and here I can see all of these methods and all of these properties of the uiimageview class let me show you one particular property here called image now this image is you can read the description down here in the autocomplete dialogue the image displayed in the image view that means that I can actually set this image property to change the image that image view is showing now I'm not going to actually do it but why I wanted to point this property out is because I want to jump back into the storyboard and show you if I click this left image view go over to the attributes inspector here you see this image attribute it's basically the image property that I just showed you see if I change the card here right that's just a visual quick way to do the same thing as if I were to do it here by using code all right the next order of business is how do we execute some code when this button is tapped on this deal button right here well that brings us to I be action functions and it's connected in the same sort of way as IB outlet properties let's go ahead and open up assistant editor and let's create some space here in the view controller side now let me just hide this panel so we can see a little bit more now before here when we were establishing these IB outlet properties we did we did it up here but now that we are connecting a function we're going to do it down here still inside of the view controller class so we have to do it you know before this closing curly bracket but we also don't want to accidentally do it inside of another function so this is you know the opening bracket of the viewdidload function and this is the closing bracket of that viewdidload function we want to do it right here this is where we can declare a new function so we can create some space here like that go ahead hold down control click on this deal button element drag it here and it says insert action outlet or outlet collection go ahead and let go and you can see that action sorry the connection type should be action if it's not just click on that drop-down and choose action and down here I want you to know it says touch up inside there are different events that this button can trigger touch up inside is just a button tap it essentially means that the user has tapped on the button and then let go of the button while still within the boundaries of the button if you open this up you can see there are different events for example touch up outside which is actually tapping on the button and the letting go with the finger outside the boundaries of the button so that doesn't really count as a tap so we're gonna leave it as touch up inside and we're going to call this Matt we're gonna call this method deal tapped and we're gonna hit connect and you're gonna see that this is essentially a function with this special IB action keyword which essentially just says that this function is connected to an event of triggered by an object in the storyboard it's got one parameter called sender which is basically the button it's a reference to the button that triggered this event and here is the opening curly bracket and here's the ending curly bracket and we're going to create some space in the middle and we're gonna add some code to execute when this button is tapped on so I'm gonna print a deal tapped like that and now we're going to run our project and we're going to tap on that button and just check the console to make sure that this is connected properly oh one thing before we do that if you've accidentally connected the wrong element to fix it would you'd go through the same exact steps as the iboutlet property so you can go ahead and right click the deal button kill that connection you can see all these different events you kill that connection under touch up inside delete the IV action and then just try it again just like before if you've accidentally made a typo here don't just don't just change the function name like that because it's going to break things right this is still connected to deal tapped right and if you don't have that corresponding function in your view view controller file it's going to break so just be aware of that all right so let's run the project all right so we're gonna click let's move this over here so here you can see in the console that this triggers alright so in this lesson you learned about how you can use iboutlet properties to allow your view controller to access and manage those elements in your storyboard you also learned about IB action functions and how they can be hooked up to events in this storyboard you learned about common mistakes that people make when they hook up their IB outlets and IB actions and how to correct those mistakes and finally you learned about app crashes and how to find a detailed error message when your app crashes now I highly recommend that you try replicating what we did in this video inside your own Xcode project and if you get stuck or your app crashes walk through those troubleshooting steps that we went through in this video and you should be fine hi welcome to lesson 9 this is a fun lesson we're going to make the card images change when we click on the deal button so if you're ready let's jump right in so here I've got our war card game Xcode project I'm looking at the storyboard and I'm going to go ahead and select that left image view now in the attributes inspector on the right hand side I'm gonna go to this image property and I'm just going to change it to a different graphic asset by choosing something different in this drop down remember that what we're doing here is just an easy visual way to do the same thing that we could do through code so essentially what I'm changing up this image asset I am really just assigning a different graphic asset to the image property of this image view object now let's jump into our view controller and see how we can do that through code just as a reminder we have references to those image view objects right we have the left image view in the right image view I want you to also note that the type you know the class is uiimageview okay that is for displaying images let's jump down to the deal method here let's erase this line and let's access our left image view using dot notation we're going to access the image property so hit dot type image and this is the same image property we were just flipping around in the storyboard you know changing that graphic asset so to do the same thing through code we would just assign you know a different graphic asset to this image property of the image view I want to draw your attention to one thing here on the left hand the column right here we can see the datatype that this property expects so this image property expects you to assign to it a UI image object this is different from UI image view UI image view is a element that displays UI image data and UI image is the data that represents the actual graphic assets so essentially what we have to do here is we have to create a new UI image object and assign it to this image property so let's just do it and you will probably make a lot more sense than me just explaining it like this alright so go ahead hit equals and then we're going to create a brand new UI image object now keep in mind that you have to type it exactly how I have it right here cuz class names lower case and upper case do matter so it needs to be capital u capital i capital i and then lower case m a GE same thing goes for these property names it has to be lowercase i image so when you're watching me type this stuff out and you're getting errors on your own laptop or a computer make sure that you're typing the right casing for your property names and your class names also another mistake I've seen is that you have to have spaces like proper spacing so make sure that you have a space before and after equal signs because you know this is not the same thing alright so what we've done here is we've created a brand new UI image object and we're assigning it to the image property of the image view however if we do this we're really not going to see anything because this is just an empty UI image object it doesn't actually have any image data to show so the cool thing about this UI image class is that it's got a method where you can create a new UI image object while passing in some input parameter to tell what sort of graphic asset you want it to represent so let me show you let me show you what that is so I'm going to open up a pair I'm going to open up the first rounded bracket and you can see all of these different functions and I scroll down or this one find this one called named right here and we are going to simply use that one here as enter and we're going to be able to specify a graphic asset name now we're going to choose one of the ones in here take a note how you're spelling this if you've just dragged my graphic assets in here then they should be lowercase C with no space in between the D and the number so let's say card five lowercase C a Rd with the number five it has to be exactly like that otherwise it's not going to find that graphic asset we're going to type card five like that so why don't we run our project right now just to see that appear all right so right now it's a three in a tenth when I click deal it's going to execute this function here and it's going to set it's going to create a new UI image object grabbing the graphic asset here and then it's going to assign that to the image property of the left image view object which is this guy right here so clicking deal there that turns into a five which is really really cool because that's the first time I think where you wrote code to influence what how in the user interface so awesome now we're gonna do the same thing for the right image view right image view dot image is equal to a UI image right and we're gonna just you can actually start typing and it's going to narrow it down for you so you can choose that this time going to choose card I think our upper limit is 14 if I'm not mistaken yeah so we've got up to card 14 alright so I'm gonna run that and this time let me just put the code on the screen here this time when I click on deal we have the ACE on the right-hand side and number 5 now if I click on deal again nothing's gonna change because it's always just running the same code right we need to basically randomize these numbers so that every time we click deal we get a different set of cards so let me tell you about how to generate random numbers it's actually quite easy so we're gonna declare a new constant let's call this like left number and you know the int datatype it's actually got a method called random that we can use right and we can specify a range and we can say the lower range that we have let's see is 2 and the upper range is 14 so we want to specify a range between 2 to 14 inclusive we're gonna go here and we're gonna type 2 dot dot dot 14 right no spaces like that and we are going to then print the left number all right now let's do the same thing with right number we're going to randomize another one same thing 2 to 14 and then we're going to print the right number so after you've typed that in let's run our project it's not going to change the images just yet but it is going to print the random numbers to the console just so we can see that we're doing this properly and move this over here so we see and it clicked a deal button oops that's still covering it up oh don't oh right here I've got that little panel hidden so click on this if it's hidden for you there we go you can see different pairs of random numbers generated now the next step is how do we get these numbers into here well all we have to do actually first thing is let's comment these lines out so we're not printing them out into the console and I would also want to point out that when you're calming taking out lines of code like this make sure that you clean it up after when you don't need it anymore so you don't want to leave too much commented code lying around because it can look messy and it's not a good practice to keep okay so remember what we what we learned about inserting variables into strings so it goes back to that instead of five here we want to put left number so I'm going to erase five and raise five put back slash open up a pair of rounded brackets and insert left number as a variable right so the string is going to read card and then whatever left number is now I'm gonna do the same thing here you raise 14 backslash put into round the brackets and I'm gonna put right number all right so let's erase these print statements oh I don't think we need that anymore okay so let's run our project here see if we get the desired result let's go ahead and click on deal so yeah this is really cool now one thing I want to point out is that if you're clicking this you're randomizing the cards and you're seeing some blank space like you're seeing a card that's just completely not there what that means is that it's looking for a graphic asset that doesn't exist in your asset library so maybe your double-check your range make sure that you know you have cards to 214 and make sure that they're named properly and maybe you might be even be missing that graphic asset completely so Chuck you have two three four five six let's check that you have all of them because if you're randomizing and you see an empty card you don't see the image it either means that you don't have the graphic asset here or you've spelled it wrong so that you know when you're trying to create this UI image object it's not finding that graphic asset in your asset library oh hey I can't stop hitting this deal button now in this lesson you learned about how to change the image of a UI image view using Swift code you also learned about how to randomize numbers and how to insert variables into a string alright so remember that you can download the project and the recap notes below hi and welcome to lesson 10 by the end of this lesson you will have finished the war card game project all that's left to do is to count the score and to update the label elements on the storyboard now doing this is going to involve writing Swift code that can take two numbers compare them and then execute different branches of code depending on what the result is in other words you're going to be writing Swift code that can make its own decisions so before we dive into our Xcode project I want to first start in a playground and I want to show you what's called an if statement which is going to allow you to evaluate a piece of data and decide what to do so the if statement starts with the if keyword and then you're going to test some sort of condition whether it's gonna be true or false and so I've got a constant integer X it's set to ten right now so I'm just gonna do a simple check and say if X is less than eleven okay so that's my condition it's going to make that test if that is true then it's going to run the code in between my curly brackets so let's create some space in the middle and I'm going print hello let's run this code here and it's gonna take off okay so we see hello in the console the reason this executes is because this condition is true right however if let's say X is 12 and I run the code again nothing's gonna be output down there it doesn't run this code because it checks and it fails the check so here's the cool thing about if statements and that is that you can provide alternatives so you can say if X is less than 11 then print hello otherwise and you would use this else keyword and you would specify another block of code to execute print goodbye all right so if we ran this code right now what would you expect to be output all right goodbye because it does this check and it fails it so it doesn't go in there and instead it comes into this else part so let me just set this to 10 and show you so X is less than 11 and that's true so it comes in here and prints hello but it doesn't print goodbye it just chooses one path or the other now here's some other cool stuff that we can do with an if statement and that is to test multiple conditions so we can say else space if and open up another block so let's say good afternoon oh I forgot to put the condition here if X is let's say greater than 12 that would print good afternoon let's make this number a little bigger so let's say 15 if X is greater than 15 then print good afternoon so what if we made the sky 20 so it would basically start at the top it would check if X is less than 11 and it's not so then it checks the next one is X greater than 15 yes it is so it prints it executes that code in there and it skips the else clause now what if none of it is true so what if I said X is equal to 13 all right so let's give that a run it falls down to this else clause because this wasn't true this wasn't true so all that's left is this sort of catch-all bucket now here's the cool part you can omit different pieces of your if statement depending on what you want to do for example you can remove the catch-all bucket you erase that and you execute it nothing happens in this scenario because none of these conditions are true and there's no catch-all bucket so essentially no code gets run now so far I've just done less-than and greater-than but you can also do a couple of different things you can do you can do less than or equal to or you can put the equals sign you could do greater than or equal to you can also do not equal to so not equal to is actually exclamation mark equals and that is testing if X is not 11 so let's take a look at this and we get hello now here's a very very important point and that is that only one branch of your if statement ever gets executed so if I had this statement where I was saying let's say something like that and I ran the code both of these conditions are true right but it starts at the top and as soon as it reaches a true condition it will execute that block of code and that's the that's it right your if statement is done so it ever only picks one path to go down even if you know this would have evaluated to true now this is very different if you write this because if you did it this way these are two different if statements so it would for to run this if statement right and tested the condition to see if it should run this block of code and then it treats this as a separate if statement and it's going to test this condition to see if it should run that block of code so that is one clear distinction to make doing it like this if and then else if combines these two conditions into a single if statement so it's it's going to be like two different paths and it's going to choose one path now instead of having two different branches like we have here you can also do three branches or four branches you can just keep changing these else if things if you want you know something like that know that this really makes sense but so you could chain as many of them as you want but just keep in mind that it's going to start at the top work its way down and as soon as it hits a condition that's true that's the branch it's going to take and it's not going to execute all your other branches now I want to go too crazy with having a whole ton of elseis because there's actually another stuff it's called a switch statement that is more suited if you have a lot of different options but an if statement is good if you want to just test a couple of branches and what else can I show you here so let's talk about the different types of comparisons that we can do we can do as you've seen it greater than you've seen less than you can do greater than or equal to you could do less than or equal to and you can test equality now notice that equality is double equal sign okay so this is testing if X is equal to two we don't use a single equal sign because remember from your basic Swift lessons a single equal sign is assignment if you write this you are trying to assign the integer two to the constant X and this is an error because X is a constant so we can't change it after anyways so if you want to compare to see if as X is equal to two you would use a double equal sign and if you wanted to compare if you wanted to test that X is not equal to two you would say exclamation equal and this is testing if X is not equal to two now this stuff can get pretty crazy because let's say you had another constant here and we're not gonna need to do this with our card game but I still want to show you just it's good to know so if you wanted to test a condition with two different variables you can either say and or or so edie is double ampersand like that so for me that would be shift and the seven I would get the ampersand so your keyboard layout might be a little different so I can say you know if Y is equal to five and X is greater than or equal to eleven then that would be true now when you use an end operator like we have here both sides of this must be true only then will it come into this branch so if we had something like y equals the six like that we ran this code then it would jump down to here right because this is not true and that kind of like cancels the whole thing the whole thing evaluates to false on the flip side let's say we had something like or which is we're actually represented by these two double pipes for my keyboard that would be shift and backslash I get this sort of symbol so for your keyboard it might be a little different but this represents or and when you have an or operator either this value it's true or this evaluates to true and that would be sufficient for it to go down this path here so as you can see if I run this code right here we're going to get hello and that is because even though this is not true this is true and that's enough because we're using or you know here's the crazy part and that's that you can use brackets to chain these things together so you can do something like this you [Applause] know so you can say like if X plus y is equal to 10 and you know either this one or either this one is true then come down here so you can express some pretty complex logic depending on where you place these brackets so let's try to run this code here and we get good afternoon but how would we make this work so x and y have to equal to 10 y has to equal to 6 so if we just did that and we change this to 4 that would actually bring us into hello so why does this evaluate to this branch well because x plus y is equal to 10 right is it 6 plus 4 is 10 and because we're using the end operator this side must also evaluate to true now what does this side say well since it's using an or either this must be true or this must be true so X is not greater than 11 right it's four that fails but Y is equal to 6 so that's true so essentially this side is true and this side is true and so that's why we're going down this path here so now we're going to implement an if statement inside of our Xcode project now let's look inside the view controller that Swift inside the deal tapped we so far have been changing the image but we have all the data we need to determine if the left side is the winner or the right side is the winner see we have left number and right number right and based on what you've just learned on the playground we can just compare these two numbers so we can say if the left number is greater than right number then right then left side wins or player wins right else if right number let's actually keep it consistent so the left number is less than right number then we have right side wins and then we do have another scenario right we're left number equals right number so we can just use an else and we can say tie now I'm not going to address this particular scenario because not exactly sure what to do but if either left side wins over the right side wins we can increase the score and then we can update the labels so if you remember all the way up here we actually haven't declared any properties to keep score so why don't we go ahead and do that vark left score is equal to zero and bar right score is equal to zero so they both start at zero you scroll down here and we're going to say left score and we're going to use plus equals 1 essentially that takes whatever number is currently inside left score and we're going to add 1 to it and we're gonna then assign or rather update the label so we do have a reference to the label because we have an iboutlet property called left score label you can see it's a type of UI label and if we use dot notation we can access the properties and methods of that score label object in the storyboard and it actually has a text property that expects a string so we're going to assign a string to it the problem is that left score is an integer so if I try to put left score see it's an int if I try to assign left score to update the text of the label we're gonna get an error because it says it cannot assign a value type of int to a type of string because remember that text properties expecting a string data so what we can do is we can actually create a new string object like that and it just has a special way where you can pass in an integer and you can represent that integer as a string so that's essentially what's happening here we are creating a new string object and we're passing in this integer and it's going to essentially treat that integer as a string or change or convert that data type now let's do the same thing with this side so we're gonna say write the score is plus equal one increasing that score and then we're going to say write score label dot text is equal to a new string object and we're gonna pass in right score all right so let's run our project now and just take a look at what we've got we've got our card game here and King is bigger than three so we have that increased score nine is bigger than seven so we have two now yeah gets one on the scoreboard ace is bigger than queen so you know cool works now don't forget to go back and write yourself some comments get into the habit of doing this so we've got randomized some numbers update the image views compare random numbers and you know you can get as granular as you want with this yeah now the last part I want to show you is about running this app on your own phone so in order to do that you would just plug in your phone with a cable plug it into your computer and if it's the first time you've ever done this you'll probably get a pop-up like if you have Xcode open asking do you want to use this phone for development and you have to click yes when you do that it's going to set up your phone for iOS development so that you can run this project on it and also if it's the first time you've ever plugged in your phone or your iPad to your computer it's gonna ask it's gonna ask on your phone do you want to trust this computer and you have to click yes or trust whatever shows up your phone so those are the two things that have to happen and then once you do have your phone connected and it's got the proper permissions and everything if you pull this drop down down you're gonna see here I don't have a device connected right now but you're going to see your device here it's gonna be like your name whatever you've named your device essentially you're gonna see it here you're gonna want to choose that okay so this pops up for me because I don't have a device connected but you're going to want to choose that and then you're going to want to just click run and essentially instead of launching the simulator it's going to launch this app on your phone and then after that you can stop your project disconnect your phone and you'll still have that app on your phone now the thing is when you do it this way Apple intends for you to do it only for testing purposes so I think it gives you about seven days before you before I won't launch anymore and you're gonna have to connect your phone again and kind of like run your project on your phone too to give you another seven days if you do have an Apple Developer account though and this is like a paid account at Apple charges you a fee every year for you to publish apps into the App Store then you'll be able to keep your app on your phone for a lot longer you'll also be able to send that out for other people to other people's phones for testing purposes and also the publish apps into the App Store not bad right look at how far you've come seriously give yourself a pat on the back you've just gone through four hours of iOS training not including the exercises and you've built their first app that you can show people to celebrate this huge milestone I want to give you a certificate of completion just visit the link below or check out the description and get your certificate and get your name up there on the wall of success stories now in terms of what to learn next I have several options for you number one you can visit youtube.com slash code with Chris to see all of the other free content and tutorial series that I have that you can watch number two if you have an app idea make sure you go and get my free seven-day app action plan which is going to help you put two an actionable list of learning objectives to build your app you can get that by going to code with Chris comm slash action plan and number three if you have some budget to spend you can check out my paid courses which actually continue from the ten lessons that you've just watched and continue building your skills and building apps and to check those out visit code with Chris comm / beginner course and lastly I just really want to thank you for learning with me you know I never imagined myself teaching iOS but I'm having so much fun every day and I feel so fulfilled hearing your success stories so if this training has helped you out in any way please reach out and message me and let me know if it weren't for people like you I wouldn't be here today so thank you again
Info
Channel: CodeWithChris
Views: 1,318,398
Rating: 4.9360695 out of 5
Keywords: ios tutorial, ios development with swift, ios tutorial for beginners, ios development tutorial, ios app development, ios development, how to make an iphone app, swift tutorial, how to make an app, xcode, how to create an app, xcode tutorial, how to make an ios app, xcode swift tutorial, ios programming tutorial for beginners, how to create apps
Id: 09TeUXjzpKs
Channel Id: undefined
Length: 206min 32sec (12392 seconds)
Published: Wed Apr 17 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.