UITableView Tutorial w/ Custom Cells - Programmatic - Swift 5 - Xcode 11

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
what's up everybody in today's video we're going to talk about how to build a table view with a custom sell programmatically no storyboards and today's video is actually the patreon tutorial of the week my patreon community every week they vote on a tutorial topic for me to cover and whatever wins that week I go ahead and create it so if you're interested in participating in that voting process check out patreon.com/scishow Allen alright let's get into the video as always let's take a quick run-through of the starter project because I took care of some things because I want to keep this focused on the table view so I do have an extensions and utilities with constants these are just my image names if you look in the supporting folder here the XE assets you'll see like these are just the thumbnails I use for the table view and we'll talk about more about this stuff when I use them I'm not gonna explain them now but when I use them I will explain them so if I'm going through this quick don't worry I do have a UI view extension to pin you know some constraint stuff my model here here's the video object and then the scene delegate here this is the initial setup for deleting the storyboard and I did a whole video dedicated to this that really walks through the step-by-step so I'll skim through it here you can check that out if you're a little confused or you can just copy this code right here for this just again allows you to start the app without the storyboard right so you see I don't have a main storyboard it's deleted but again that video walks through that step by step we're trying to focus on the table view and then here's just the view controller I have right now literally nothing just the background equals blue and if we run this real quick you can see what we're starting with just a blue view controller just to show that it's up and running and working but we're gonna we're gonna create this table view right now alright so the first thing we're gonna do let's just delete this view controller because we are not using this get add here this was just to to get everything up and running here to get the starter project going so I move the trash that view controller is gone so the first thing we're going to do is file new file we're going to create the view controller that has the list of the the table view so cocoa touch class hit next the reason I pick cocoa touch class is because I can do this UI view controller and it kind of like fills in some boilerplate stuff for me I don't really type it all from scratch so if I were to just do a swift file so they're gonna name this video list VC I like to shorten view controller to just VC because it makes the file names all super long it's pretty redundant that's just a personal preference thing so here's our video list vici and again let's go ahead and delete this stuff but I get my my V to load everything up here and then of course the first thing write the name of the tutorial here let's go ahead and create our table view so of our table view equals and we're gonna initialize a UI tableview and like that so there we go you've created your table view we're done if only it were that easy right so we're gonna have a main function here that does a lot of the work called configure table view and we're gonna do a couple things here first of all when you're doing programmatic UI you know when you have the storyboard the views are automatically added the sub views are automatically added to the views I always mix that up so right now we're gonna go ahead and do view dot add sub view table view that we created so what this does is this actually this table view that we created on line 13 like it's out in no-man's land right now until we actually add it to the view and the view is like the main view of the view controller until we add the sub U of the table view it really doesn't exist in this view controller I mean it exists but you get what I'm saying so now we made it official it is a part of this view and like I said there's a few things we need to handle here so we need to definitely I'm gonna write these and comments for now set the delegates set row height register cells and set constraints so this is kind of like the to-do list this is what this function is going to do right so let's go ahead and let's start with the delegates and I'll explain that after I do that so I am you could potentially do all these in this function but I'm intentionally breaking it out maybe overdoing the abstraction but I think that's gonna help it make more sense to maybe the beginner or somebody that's trying to learn table views if I break out each task and do its own function again this may be a little overkill but just doing that for you so it's go ahead and do set the delegates sets table view delegates and then here we do a table view that delegate equals self and I'm gonna explain this line here in a second table view data source equals self so well I mean let me actually do this next part and then I'll explain the delegates here so you can see it says cannot assign value of type video this VC to type new our table view data sort they'll get an data source so basically what I'm doing is I'm kind of like signing up this view controller so self is this view controller the video list VC so I'm signing up the video list VC to be the delegate and data source of this table view but it's saying like I can't do that so I need to have this view controller conform to UI tableview delegate and UI tableview datasource sometimes you'll see people do that like right here they'll type it you know here up top but I like to do this in extensions down low to keep my code compartmentalized and separated I think it's visually nicer and like helps you find things quicker so writing an extension for video lists VC and that now here we're gonna conform to UI table view you can see delegate and then UI tableview datasource you don't have to kind of break it out a new extension again just personal preference here so in this you're gonna get me I'm gonna get some more errors here so video list does not conform to the protocol UI tableview datasource do you want to add the protocol stubs yes I do so this will do it for you so there's two main functions you have to implement here and by clicking that it added that automatically so you need number of rows in sections so the two main things table views need to know is how many cells am I going to show and that's basically what this does so a number of rows in section right we're only doing a table view with one section but the main question hey how many rows do I show and then here you tell it so you're gonna return an int you see this returns an integer so a number for right now we're gonna return 10 that is going to change in the future but we're just doing this right now to kind of silence the errors and get the table view up and running so first thing how many cells the second thing what cells am i showing right that makes sense the table you would probably need to know that so here we're going to just return a UI tableview cell just a default one again this is just for now just to shut up the errors and to get the get it up up and running we're gonna do a custom cell in a little bit so going back up to our configure table view and also by the way as I'm going through this and building this I am going to do a summary at the end so if you feel a little lost you know you didn't quite get something one you're gonna see the process being made and then once you know it's all done and you've seen it I'm going to summarize everything at the end and hopefully that pulls it all together for you so what we've done we set the delegates so it's going to call that function set table you delegates cool I can delete this comment that's step one set row height we're not gonna do another function for that we're just gonna do that so table view dot row height equals to 100 and that's because because I have a big image in a title I want my cells to be taller you can put whatever number you you want and I am hard-coding this more advanced table views where you have like dynamic stuff because you don't know like maybe you're bringing back like user comments and you don't know if somebody wrote a paragraph or just one line so you want the cells to be dynamic that's a more advanced topic but that is possible now we want to register cells we're gonna come back to this because I haven't created my custom cell yet my video cell so we're gonna come back to that so set constraints we can do and this is where the extension comes in that I have so a table view dot pin now this is the extension I made and I'm gonna go back and explain that to super-sorry view so basically what this is doing is it's pinning everything to the edge if you're familiar with constraints at all you know you have to pin the top the sides and the bottom of the view well what this extension does and I'm gonna go to it right now it's basically an extension that works on any UI view and it has built-in constraints that just pins it to all the edges right so to see the top anchor is equal to the super view top anchor leading is equal to the super view leading trailing bottom etc so this is a very common type of constraint that you want to set or you're just pinning stuff to all the edges so that's why I having an extension is pretty useful for this kind of thing that way anytime you want to pin to just the edges you can just go ahead and do what I did here in the video list we see you want to move this up here the video lets you see we're just tableview that pin to view and in your view controller it keeps it nice and clean and I like that because one of the problems with programmatic UI at least one of the things I don't like about it for the record my projects are usually a mix of both storyboarding and programmatic I'm not a one way or the other kind of person I like both but the the downside to me of the programmatic UI is when you're creating all your constraints right so having you have all this code all throughout like your view controller potentially so I'll I kept tracking that away that way in my view controller it's just nice and clean table view dot pin to view done alright so now I can delete that comment again we're gonna come back and register the cell in a second here but now in viewdidload I can just call configure table view and this is how I like to have my view to vote I don't like I don't like a lot of logic in my view did load and the reason being is because I like to like the viewdidload and the view will appear that's like basically tells you what the view controller does so I like my view two loads to read just like a list of commands like configure table view fetch data do this okay so you know what's happening on the view controller I've seen a lot of you did loads that are like 30 lines long and have a lot of logic don't do that so now before we run it let's go back to our scene delegate remember where we set up see I have an error remember where we set up the how to show it without the storyboard from the launch well that was launching with our original view controller remember that we had that we deleted now we have this video list VC so let's do that and it's actually not presenting this video list VC if you can see I'm creating a navigation controller in the root view controller of the navigation controller is the video list VC right so I'm basically presenting the navigation controller inside that navigation controller you have the video list vc which is what you see just one little caveat there so now if we run this so you can see our empty table view right we gave it a number of rows now we need to tell it what cell to put in it right because we just have the default UI tableview cell which has nothing in it so we're gonna create our custom cell right now populate that with the videos and we should be good alright so back in our video list VC let's do file new file we're gonna create a uitableviewcell file for our custom cell so again cocoa touch class so we can get some of the default stuff we're gonna call this well let me go ahead and do UI tableview cell right and then let's call this video cell hit next create so here I have my video so right here I can go ahead and delete this and actually delete this so getting the default stuff you know doesn't always help so much but I didn't have to type this out at least but anyway so there's an override method when you're doing this programmatically so when you have storyboard you don't have to do this override init method but programmatically you do so go ahead and type this out real quick okay so if we're not mine it method as you can see then you call the super so pretty much every time you overwrite in an it you I don't say every time but most likely you're going to want to call the super init method so but you see here any time you do a require an initializer you must have the other one sorry the required in it with coder with the fatal error coder has not been implemented all right so now that we have our NIT methods we can start creating like the the image in the title right so normally table view cells like the default ones do come with an image in a title but I want to customize this one so that's why we're doing this so of our video image view and this is a UI image view we're gonna initial ops I don't want to that so that's setting the type right there you can just Swift us type inference which is a nice thing about it so you just do when you initialize it you already know what type it is you I I can't type image right there at the top you have you cool and then var video title label equals UI label so those are the two components we're gonna have here I always like to line them equal signs personal preference thing just me so that there now I have that so now we need to configure these right and also like set the constraints to tell the cell where to put the image where to put the title so we're gonna go ahead and do that now and again I'm overly breaking things out because I think that's easier to understand so we're gonna have two different configure methods here so well first of all again just like with the table view the very first thing you need to do and I've forgotten this a lot when I've done programmatic UI what'll happen is you'll set everything up and it's not working and you will have forgot to add the view to the I'm sorry the sub view to the view I always flip that so here we're gonna do add sub view video image view and then add sub view video title label so there we go so now our views are added to the sub view so now let's go and configure them so funk can figure image image view sorry typing sorry again I'm typing around my mic I know I say it every tutorial but it's difficult function configure title label and this is just kind of like the little things that you do as you'll see here so for example I want to configure my image view by doing video I want to I'm setting the corner radius here so video image view layer corner radius equals 10 it's good and then video image view dot Clips two bounds equals true so this is what allows it to actually show the corner radius and then in my title label I do want it to so I'll explain after I type it video title label number of lines equals zero so what that does is say my title goes to two lines it's going to word wrap it automatically and look fine and you'll see that in a couple cases here and then video title label dot adjust font size to width equals true so what this means is it'll shrink the font size if like it won't truncate it right if it's too big the font size will shrink a little bit so just small label configurations to to get that working so before I forget let's you know call these actually so configure image view in my initializer method and then configure title label so again when that when the cell gets initialized we're adding the views and then we're configuring them how we like it now the last thing we need to do here well second the last thing this is just the UI setup is to set the constraints and and I do have like some code snippets because I don't think you want to watch me type out the constraint stuff but I will explain it so func set image and then let me do my command shift l for my code snippets here cell image constraints let's go ahead use that done you don't need this make that look better so and I'll go and explain that real quick let me get the the title ones into in there too so func and then command shift a little pull up any save Co step is you have I have that BAM there we go so I'll walk through this real quick again I just kind of saved you the time of me sitting there typing all that out but so first thing you want to do is translate Auto resizing mask into constraints equals false basically if you want to use auto layout you have to do that on pretty much everything so how I'm doing the video image view right I want it kind of off to the left like you saw in the initial image so but I want it centered in the cell so the center why like the y-axis is equal to the center y-axis of the table view cell and then the leading anchor which is the left side I want it twelve away from the leading the left so if you're gonna see a padding of 12 on the left side so that's what that does and then the height anchor is equal to 80 so I basically just hard-coded the height because I know my cells are 100 right if my cells were dynamic I would have to do something a little different here but again that's more advanced for this basic table view I know my rows are gonna be 100 so I want my images to be 80 to give a little bit of space in between and then this is kind of a little tricky constraint where I'm doing like an aspect ratio constraint so I know my titles are sixteen by nine right that's the aspect ratio kind of like the YouTube video thumbnail so whoa I'm setting the width is the width is going to be now it could have hard-coded this but I wanted to show off this constraint but the width is going to be the video image view the height basically times sixteen by nine to give it that aspect ratio so if you always want to have the same aspect ratio so you don't have to hard-code the height and width this is a good way to do that so that's the image constraints and then the label constraints so auto layout constraints are very repetitive once you understand them so I'll kind of breeze through this again the auto masking and extrange see ORS gonna set that false to use auto layout again I'm centering the Y to the center of the cell I want the label to be in the dead center of the cell just like the image vertically leading anchor now we're pinning the leading anchor to the video image view right so I have the image view on the left and the label on the right so I'm pinning the label to the image so you can see I'm pinning it to the images trailing anchor so that means the right side and I'm giving it a constant of 20 so I want the the spacing of 20 and then you have to activate them that's what all this is active equals true is you have to make the constraints active and then I'm hard-coding the height to 80 it's just to be the same as the the image and then the trailing anchor is to the cells trailing anchors to the right side of the screen and then when you're doing the trailing anchors you have to do like negative numbers that always confuses me but so negative 12 so I want 12 padding just like I have 12 padding on the Left 12 padding on the right and that's setting up the UI of the cell let me call those so I don't forget set image constraints set title label constraints cool and we're doing all that in our an it method but just like our viewdidload like I said I like to have that just be a list of commands this is what we're doing right we're configuring and we're studying constraints now there's one final function here that we're gonna have to do because right now on the table view right it just has a D has a just a default table view cell we need to tell we need to have this be a video so now so for that we need some videos so again the two things a table view needs to know is how many cells am i creating and what cells am i putting in there right so before we just gave it a default number and a default cell now we're actually gonna populate that with our custom cell so again I do have an extension for some dummy data so let's go ahead and do command shift l the dummy data extension and here you see the comment says generating dummy data where this data gets created is likely to be different in a real app and it's likely from a network call you'll see that a lot but again to keep this focused on the table view I didn't think you wanted to watch me type out all this stuff but I'll walk through it so I have this function called fetch data and again you'll commonly see this in a real app as like a network call like it's fetching from the Twitter servers and all showing all the tweets but this is just dummy data so this is returning an array of videos remember the video object I had here a video just has an image in a title so that is what this is returning an array of those so for example video one I'm initializing with an image and normally when you initialize an image you have to do UI image dot and then type out the name but that's what this constants file was for where I have my struct of images so where everything is like has already been coded in here like I've already initialized the image right so that way I can just do images 90 to get this and the reason you do that is so you don't have to type out these strings every time because when you're typing out strings like you're liable to have a typo and in an image if I were to have a typo like if that were just 99 like my image wouldn't show up it would be an error so you want to do that to avoid typos here and so now I can just do images dot no storyboard and the cool thing is you also get like the autocomplete too when you do this so if I do images dots you know you can see these are all the images I created here so no storyboard so that's a benefit of creating that constants file - and then I did just type in the string for the title of each video and I created ten videos as you can see returned an array of video one two three four five six seven eight nine ten and that's what this is returning here so that's the quick dummy data explanation and one basic thing about a table view is a table view pretty much always takes an array of something so I want a VAR let's call this videos we're gonna create an array of the videos here so it is going to be of type and then the array video and right now this is just an empty array because that's how you're gonna do it normally because again like I said a lot of times you'll be fetching data from a server so I have my whoops this should be videos because it's plural so I my videos which is an array of videos and you can see that's what I created down here with fetch data so the first thing I want to do or one of the first things I want to do here in view to load here is to fetch the data so let's say videos equals fetch data right so what fetch data does remember it returns this list of video this array of videos so basically I've just populated this empty array of videos with all that stuff I created down there so now I have an array of videos to pass in to my table view right a table view is basically a list of stuff well what is that stuff you're listing that's what this array of videos is so back down to the two main questions right how many cells do I show what cells do I show so now we know that how many right because it's we're gonna do instead of returning ten we're gonna do videos dot count so a videos that count is just the number of videos in the array if that's how many cells were going to show right that makes sense so now the final question we need to answer is what cell do we show so back to this register cells here we have to register the cell let's go ahead and do that and that's table view so registering it on the table you dot register and you know you'll get the autocomplete here we want cell class so the cell class is going to be video cell that's the custom cell that we created and you go do a dot self there and then for reuse identifier so this is where you have to give it a string if you've built the table view on storyboard you know this is just a field that you fill out you may be familiar with that so this is the same thing that we're doing here just programmatically so we're registering the cell with the reuse identifier of video cell and this comes into play down here when we're configuring our cell so okay cell is registered we're good to go there one quick thing I forgot to do is give the give this a title here so this is just the title of the viewcontroller equals in you passing a string Shaun's videos and that's just for the UM the navigation bar that the title up there you'll see that when it pops up so now the last piece of the puzzle here is actually sending the custom cell to the table view so instead of returning a UI tableview cell we're actually gonna add some code in here we're gonna create this custom cell so let cell equal table view dot DQ and then reusable cell with identifier this is the identifier we're gonna talk about this DQ stuff right on how the actual table view works this is part of the whole wrap up at the end where I kind of hopefully make all this makes sense and then again the string is video cell but remember I just talked about how like having these strings and typos is dangerous right like if I would had a typo there in video cell that didn't match up with this string perfectly it wouldn't work everything would break so what I like to do for my cells here is make a little struct at the top so struct and then this is cells you static let video cell equal video cell and the reason you do this is that what you only have to write this string once so now instead of having this string here I can do cells dot video cell and you get the autocomplete here and then same thing here cells dot video cell so that way I don't have like string Li type stuff everywhere so okay this warning will get fixed here so now we have our cell except one thing I forgot to do here is you need to cast this as a video cell and the reason we're gonna do that is because we want access we want to tell it it's a video cell because we want access to the functions on the video cell and I'm missing one key function here that we're going to need so this is like what makes the magic all happen so I saved it for last and again I'm gonna do a recap at the end here so I do a function called func set and then it passes in a video that video object and then here is where we basically configure the cell so like I said video image view image equals video dot image so what's going on here is and I'll explain this at the end - but we're passing through a video and whatever video get passed on the cell like remember the video is the objects that we created down here like each one has an image each one has a title so back in the video cell now that I've been passed in a video I'm gonna set that specific cells image view image to whatever image is attached that video that I passed in and then the same thing with the title so a video title label dot text one blank there equals video dot title alright so we're just passing the image in the title and then back in the video list VC this is where we're actually gonna use it here right so we created our cell that is a video cell now we need to determine which video I'm gonna pass in and I'm gonna explain how itself a row works here in a second so now we need to create a video let's video equal videos so this is the array and this is the index of the array and this is gonna be confusing if you haven't seen this but I'm gonna explain it in XPath dot Rho and then cell so now this is why you know when creating a video cell I want access to this function that I just created called set video and then we're passing in the video we created online 54 and then now for this so we don't want to return a default table view cell anymore we want to return the cell that we created here and configured online 52 and 55 so okay let me explain this function because this is kind of like I said where the magic happens so the way self row at index path works is this gets called every time a new cell comes on the screen right you see this DQ reusable cell so if you imagine a list of like a hundred cells long like it's not like your phone is moving up and down that that list right it's your phone only generates enough cells that are on the screen and what happens is just before a cell is about to come on the screen it gets configured so when you're swiping real fast up and down on Twitter like those tweets are getting generated like super fast in the tableview cell before it comes on right it's not like the long list already exists and you're just kind of moving up it so that's what's going on here so basically this function as you're scrolling gets called a lot so that's also we know performance issues you want to make sure not a lot of heavy performance stuff is going on here so that's what's going on every time we're creating this cell and we're picking what video it is so video at index patro and the cell does have in the next PATH think of the index path remember I have 10 here so I'm gonna have 10 index paths so you know if it's that index path you know 7 well I think they're 0 indexed so I guess this would be index path 6 that you know it's going to get this video so that's why here when I say what video in the array do I want so index path dot row is either going to be you know 0 through 9 right here because it's index path so that's being passed in so I know which video to grab out of the array and then I know which video to grab out of the array so I pass that into cell dot set which again in my video cell here sets the image and the title appropriately for the right video so that's the gist of how self row in the next path works again just one key thing one key unlock from you and I was trying to understand this I like for some reason I used to think this only happened at the initial setup of the table view but once I kind of realized that no this gets called all the time like every time this that's table view is moving up and down this is getting called once I kind of realized that this all started to make sense for me so hopefully it makes sense for you to but that wraps up the code let's go ahead and run this and see what we got we should have a working nice little table view here BAM Shawn's videos remember that was a title I did here's the image you see the corner radius we put on the image and you can see the aspect ratio is being kept here's the title you can see all the constraints in action and then as we're swiping up so like I said right now like 1 2 3 4 or 5 6 7 cells are on the screen so that means like you know the the phone only generates and may generate one or two above for the little buffer that's getting too technical but anyway so as I'm scrolling you know the cells are being generated like I talked about so all right let's give the quick recap the rundown of everything that's going on here in the table view cell right so again the first thing that happens is I am fetching the data because I am I want to populate this array of videos right because a table view needs a list of stuff to show right again the table U is just a list of things what are you showing and that's where these videos come in so you create an array of videos the table view is always gonna need an array and then we're configuring the table view which again you have to set the delegates many many errors like if it's not working you will have forgot to set the delegate and data source so you have to do that and again self is the video list VC that's what you're setting and then whenever you do that you have to conform to those delegates so UI tableview delegate and UI tableview datasource again those are these functions here now there are many more functions these are just the two that are required for example if I type in here table view you can see like did select row did deselect row did highlight did end editing good unhighlight can edit like there's a lot right but this is just the basic table view so table whose are real powerful you can do a lot for example like did select is what happens when the user taps the row this is usually when you would like send them to a new screen right the master detail view we're obviously not getting into that now but I wanted to point out that there are many many more methods but again the two most important ones the two required ones how many cells are we gonna show what are we gonna show in it right so we're gonna show the number of videos we have in our array cool and then here we're gonna show you know we're gonna create the cell the video cell that we created the custom one we're gonna tell it what video to put in that cell again the index path is the the number right so in this case it would be you know 0 through 9 and 0 index on 1 through 10 and then we grab the right video and then we pass that video to our cell which if we go to our cell it will set up the image in the text appropriately and then all the other stuff in the video so again is just the constraint stuff and remember the thing I said about the programmatic UI is like you just get a lot of like it's not messy constraint code but it's just it's a lot of code doing that that way so so where this file may not may look like a lot if this were in storyboard it would be like pretty much just this but anyway I digress and back to the video list we see that like I said you're returning the cell after you you basically set the video and that's that so hopefully you found that helpful building a table view programmatically if you have any questions please leave them in the comments happy to answer them I put out new tutorials all the time so if you found this interesting consider subscribing and we'll see you in the next one
Info
Channel: Sean Allen
Views: 44,485
Rating: undefined out of 5
Keywords: programmatic table view swift, swift tableview programmatically, custom tableviewcell swift 5 programmatically, uitableview programmatically swift 5, swift uitableview programmatically, Swift UITableView Tutorial, Swift TableView, Swift UITableView Custom Cell, Swift TableView Cell, TableView Swift 5, Swift TableView Tutorial, Swift TableView in ViewController, table view tutorial swift, tableview tutorial in swift 5, xcode tableView tutorial, Swift 5 tableview tutorial
Id: bXHinfFMkFw
Channel Id: undefined
Length: 30min 49sec (1849 seconds)
Published: Fri Sep 13 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.