AutoLayout Constraints Programmatically (Swift 5, Xcode 12, 2020) - iOS Development

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] what is going on you guys welcome back to another swift video in today's video we're going to take a look at how to apply auto layout constraints fully programmatically kind of ins and outs of it good practices bad practices all the good stuff all fully encode so if you don't know auto layout is a system to apply constraints to layout your code in a automated fashion uh and oftentimes people kind of teach it with storyboard which is great and all but i think seeing it through code is pretty helpful as well so uh if you are excited for the video make sure you destroy the like button as per usual uh hitting that like button really helps out the video and channel grow if you are a returning viewer hit subscribe while you're at it i also want to shout out to all of you and say a big thank you for helping this channel across 10 000 subscribers we've come a long way got a long way to go that said let me stop going on and on open up xcode get excited and let's dig into auto layout in code quick pause before we get into the video if you haven't seen it already i am hard at work putting together ios academy dot io a community where all of us ios engineers can come together learn how to build some of the top apps like facebook youtube and instagram in addition to interview prep to land some of these ios roles at top tech companies so if you're interested in the free and premium content to come head on over to ios academy dot io and enter your email address in the waitlist form and you will be notified as content becomes available that said let's get into the video let's begin by opening up xcode and creating a new project we're going to go ahead and stick with our app template here and let's name our project constraints constraint layout in code make sure your language is swift life cycles ui kit and interface is storyboard let's continue let's go ahead and save it and before we dive into the code let me go ahead and pick a simulator over here and let's hit the run button that way everything is nice and ready for us to actually see our code in action let me expand my xcode window and finally let's jump to our view controller file so as you might know already there is this notion of constraints and auto layouts to layout our views on the screen other than auto layout you could use frame based layout where you specify x y width and height of every frame traditionally auto layout a lot of people teach it through storyboard and how you connect you know your outlet to something and you can in fact do auto layout fully through code and that's what we're going to be looking at today so before we get into uh some of the conceptual explanations of why we should do things a certain way let's start off with an example since i think seeing it is often pretty helpful so i'm going to create a basic view here called my view we're going to say my view dot background color is link which is just a blue color and we're also going to see my view translates uh auto resizing mask into constraints is going to be false if we don't specify this our constraints will not apply properly in view to load we're going to want to add this as a sub view and i'm going to go ahead and create another function called add constraints and we're simply going to call this function right after we add the sub view just like that so once you do that hit command r you'll notice you don't see anything different here your view is in the hierarchy but there's no frame assigned to it so the way we get it to late self foul is of course with constraints so there's a bunch of different constraints you can pick from uh there's width height pinning if you want the view to be equal to the left right top and bottom there's multipliers and a whole heap of things to look at so let's start off with the basics so we're going to create an array called constraints and we're going to initialize this to be an array of ns layout constraint going to add our constraints and then we're going to activate our constraints so activating the constraints is pretty straightforward you can just say ns layout constraints activate and pass in your array of constraints to be activated uh think of activation as applying the constraints uh to the actual view in question and adding is we're just gonna append to the constraints collection which constraints we want so a simple append and we're going to apply four constraints to our blue my view and we want to start off by pinning the view to each side of the screen so it takes up the entirety minus the safe area so we don't want to overlap the status bar or this little home screen indicator thing at the bottom as well so we're going to say my view dot leading anchor so leading and trailing refers to left and right we're going to say constraint and we want equal to and we're going to say let me close this right panel see have some more room and we're going to say it's equal to the current views safe area layout guide dot leading anchor and i'm actually going to copy and paste this to have a total of four and we're simply going to change these up so the next one is trailing so change that there and here next one we'll do is bottom anchor which is the bottom of the screen of course so change that there and here next one is top anchor go ahead and put that there and put this here and that's all we need to do to actually pin our my view which is blue to the entirety of the screen so go ahead and hit command r and let's see if we did that correctly so if you run it you'll see that the blue view now takes up the entirety of the screen and in fact it also does respect the safe area of the status bar and the home screen indicator at the bottom one other thing you'll notice is that in landscape it also now takes care of things like the notch as well as the bottom here you will notice there is some padding here and we will need to have other logic to handle different rotation but we're not going to really dive into that in this video but let's take a look at other things we can do so these are the constraints to my view now let's say we had a secondary view so let me go ahead and copy and paste that i'm just going to say second view here and we're going to say the color is system red and we're going to add a second view into my view just like that and we're going to apply four more constraints and these ones are going to be applied to the second view so go ahead and simply change this and all of these and we're going to have this instead of be referencing view that top anchor this is going to be its parents so my view but one thing that we are going to change now in this is we can say this equal to part which is great i'm going to line break it to give ourselves a little bit more room but this can actually take another parameter called constant and constant basically specifies from that anchor side how much padding do you want how much of a margin so i'm going to go ahead and say now let's just run it and see what that looks like and see if we did it correctly all right cool so we have our blue view we have the red view inside of it and it's 120 from the left so that works so now we can of course apply that constant parameter to each of these other constraints so we can have it be 120 from each side just like that and you can see it's a little weird because it's actually pushing down 120 from the top and 120 from the left and the trailing uh or the the right side and the bottom side are not really respecting their 120 because there's a conflict right because you're saying there's 120 from the top and 120 from the bottom so you actually need to apply negative constraints for the constants to get it to render correctly now let's see what other constraints are available to us so let me just go ahead and delete that delete that and we're going to say second view and if you just type in a constraint rather if we just type in which constraint you want so let's do there is a with anchor and then you do constraint you can see you can do a constraint equal to something with a multiplier you can do equal to multiplier with a constant as well let's take a look at the multiplier and see what that looks like so what let's say we want this to be the same width as our container which is in my view dot with anchor and we want the multiplier to be 0.5 in other words we want the width to be one half of our equal to so our my view let's also do that for the height just like that and let's say this is the height anchor and if you go ahead and run it i believe we'll get some errors in our console um let's see so actually if we don't specify one of these let's comment out the height we should see some errors in our console if i'm not mistaken okay it looks like we don't so let's see what i can screw up to get some errors in our console going on so let's get rid of this translates auto resizing mask and i wanna there we go there are those errors so what happens sometimes is when you apply constraints if the auto layout engine cannot figure out um how to satisfy all those constraints simultaneously it'll throw a bunch of errors like this in the console your app will not crash but basically nothing is going to lay out properly and all this is really saying is hey wait a second you told me to apply these constraints but either they're contradictory or i mean unable to do it for one reason or another right so in this case we commented out translates auto resizing masking constraint so it's complaining but if we had a contradictory constraints like if we make this leading let's see what go what goes ahead and happens so in this case we still have errors because we're saying the leading can there's two leading constraints on this my view and they're equal to two different things so the layout engine which drives auto layout under the hood is basically like wait a sec man i have no idea how to do this and when you read through this whenever you see a stack trace like this rather than a stack trace rather a warning kind of dump in your console you should really look at two things one thing is if your kind of mathematical constraints are satisfiable together aka nothing is contradictory and that you have this specified to false so let's go back and take a look at that width and height constraint so the width and height constraint is pretty simple it uh gives you you know the width and height that you want and right now we've set it to be 0.5 as the multiplier so it'll take my views width and height anchors and it'll set it to 0.5 of it or half of it you can set it to be 75 and 1. and let's see what that looks like so you can do that so looking pretty good and let's see you can also change this to be a constant so let's say we want this to be 200 by 200 and let's see if we can get rid of that i don't think we can let's go ahead and run it whoops looks like i forgot a parenthesis there let's go ahead and run that and see what we get so we see the red view actually takes up the entirety of the screen so what we want to do is go ahead and open up that constructor again let's see what else is available to us so we have equal to we have greater than greater than less than let's go ahead and take a look at this equal to again so the first parameter here is what constraint do you want this to be equal to uh the next one is a multiplier and then there's also a constant so actually instead of looking at this since we already kind of took a look at width and height let's take a look at center x and center y so there are other constraints as you can imagine one of them being your center y anchor and you can have this be equal to similarly your parent containers center y anchor and let's do that for the x as well and let's see what that looks like and the name kind of gives it a way of what it's going to look like but this is a pretty practical example of how you would want to go ahead and center things so let me actually change this to be a multiplier again and let's do 0.5 and 0.5 let's go ahead and run that and you'll see that we have the same height as before so 50 percent the width and that 50 percent the height but now we have it pinned to the center of our screen and the cool thing is what you saw there is when we rotate it the height actually completely changed so the height now is reflective of the height in this setting and vice versa in this setting and it still stays centered and pinned to the center of the screen hence the center x and center y constraints so let's see what else so the last thing i'll mention before wrapping up here is i personally do prefer frame based layouts so i think it is subjective to a degree however the one place where i do often find myself defaulting to auto layout through code is laying out content in table view cells so the nature of a table view cell and the way we're doing cell height calculations is dynamic right the content is going to derive the height of a table if you sell using constraints often simplifies your life a little bit versus calculating everything manually at the end of the day my consensus on this is in terms of layout do what you think is easiest for you to get your app laid out correctly in all different phone sizes and ipad and so on and so forth uh one being better than the other highly subjective do what works for you and uh that's kind of the extent that i recommend people take a look at it so that's it that's all i've got for you guys today if you haven't destroyed the like button already make sure to do so helps out the video and larger channel quite a bit hit subscribe if you haven't done that already yet and you enjoyed the video or continue to watch these videos we just crossed 10 000 which is pretty crazy i started this channel as you know a way to pay the knowledge forward since i learned from youtube over a decade ago uh leave any comments down below of any questions you guys may have feedback video suggestions so on and so forth thank you so much for watching i'll catch you guys in the next one
Info
Channel: iOS Academy
Views: 11,156
Rating: undefined out of 5
Keywords: swift 5 tutorial, swift 2020, swift, swift 5, swift tutorial, swift for beginners, swiftUI 2020, swift programming, swift basics, swift apps, make iPhone app, swift make first app, swift autolayout, auto layout, swift constraints, auto layout beginners, auto layout in code, swiftUI layout, view layout, auto layout constraints 2020, swift 5 auto layout, how to use auto layout, swift frame layout, swift auto layout, swift cell height, auto layout in swift 5, iOS, app, layout
Id: HuCx6dGaY1g
Channel Id: undefined
Length: 15min 57sec (957 seconds)
Published: Thu Oct 08 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.