iOS学习之table view controller、table view cell

A table view controller, like many objects, has more than one init method. There is:

initWithCoder, for view controllers that are automatically loaded from a storyboard

initWithNibName, for view controllers that you manually want to load from a nib (a nib is like a storyboard but only contains a single view controller)

initWithStyle, for table view controllers that you manually want to create without using a storyboard or nib 

 

There are four ways that you can make table view cells: 
1. Using prototype cells. This is a probably the simplest and quickest way. You did this in ChecklistViewController.

2. Using static cells. You did this for the Add/Edit Item screen. This is limited to screens where you know in advance which cells you’ll have. The big advantage with static cells is that you don’t need to provide any of the data source methods (cellForRowAtIndexPath and so on).

3. By hand, what you did above. This is how you were supposed to do it before iOS 5. Chances are you’ll run across code examples that do it this way, especially from older articles and books. It’s a bit more work but also offers you most of the flexibility.

4. Using a nib file. A nib (also known as a XIB) is like a storyboard but it only contains a single view controller or in this case a single custom UITableViewCell object. This is very similar to using prototype cells, except that you can do it outside of a storyboard.

When you create a cell by hand you specify a certain cell style, which gives you a cell with a preconfigured layout that already has labels and an image view. For the All Lists View Controller you’re using the “Default” style but later in this tutorial you’ll switch it to “Subtitle”, which gives the cell a second, smaller label below the main label.

Using standard cell styles means you don’t have to design your own cell layout. For many apps these standard layouts are sufficient so that saves you some work. Prototype cells and static cells can also use these standard cell styles. The default style for a prototype or static cell is “Custom”, which requires you to use your own labels, but you can change that to one of the built-in styles with Interface Builder.

And finally, a warning: Sometimes I see code that creates a new cell for every row rather than trying to reuse cells. Don’t do that! Always ask the table view first whether it has a cell available that can be recycled using dequeueReusableCellWithIdentifier. Creating a new cell for each row will cause your app to slow down, as object creation is slower than simply re-using an existing object. Creating all these new objects also takes up more memory, which is a precious commodity on mobile devices. For the best performance, reuse those cells! 

posted @ 2016-05-01 09:24  XuDeHong  阅读(238)  评论(0编辑  收藏  举报