Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Beginning iOS5 Development.pdf
Скачиваний:
7
Добавлен:
09.05.2015
Размер:
15.6 Mб
Скачать

CHAPTER 8: Introduction to Table Views

221

Sections have two primary purposes. In a grouped table, each section represents one group. In an indexed table, each section corresponds to one index entry. For example, if you wanted to display a list indexed alphabetically with an index entry for every letter, you would have 26 sections, each containing all the values that begin with a particular letter.

CAUTION: Even though it is technically possible to create a grouped table with an index, you should not do so. The iPhone Human Interface Guidelines specifically state that grouped tables

should not provide indexes.

Implementing a Simple Table

Let’s look at the simplest possible example of a table view to get a feel for how it works. In this example, we’re just going to display a list of text values.

Create a new project in Xcode. For this chapter, we’re going back to the Single View Application template, so select that one. Call your project Simple Table, enter BID as the

Class Prefix, and set the Device Family to iPhone. Be sure the Use Storyboard and

Include Unit Tests checkboxes are unchecked.

Designing the View

In the project navigator, expand the Simple Table project and the Simple Table folder. This is such a simple application that we’re not going to need any outlets or actions. Go ahead and select BIDViewController.xib to edit the GUI. If the View window isn’t visible in the layout area, single-click its icon in the dock to open it. Then look in the object library for a Table View (see Figure 8–4), and drag that over to the View window.

The table view should automatically size itself to the height and width of the view. This is exactly what we want. Table views are designed to fill the entire width of the screen and as much of the height as isn’t taken up by your application’s navigation bars, toolbars, and tab bars.

After dropping the table view onto the View window and fitting it just below the status bar, it should still be selected. If it’s not, single-click the table view to select it. Then press 6 to bring up the connections inspector. You’ll notice that the first two available connections for the table view are the same as the first two for the picker view: dataSource and delegate. Drag from the circle next to each of those connections over to the File’s Owner icon. By doing this, we are making our controller class both the data source and delegate for this table.

After setting the connections, save your nib file and get ready to dig into some

UITableView code.

www.it-ebooks.info

222

CHAPTER 8: Introduction to Table Views

Figure 8–4. Dragging a table view from the library onto our main view. Notice that the table view automatically resizes to the full size of the view.

Writing the Controller

The next stop is our controller class’s header file. Single-click BIDViewController.h, and add the following code:

#import <UIKit/UIKit.h>

@interface BIDViewController : UIViewController

<UITableViewDelegate, UITableViewDataSource>

@property (strong, nonatomic) NSArray *listData;

@end

All we’re doing here is conforming our class to the two protocols that are needed for it to act as the delegate and data source for the table view, and then declaring an array that will hold the data to be displayed.

Save your changes. Next, switch over to BIDViewController.m, and add the following code at the beginning of the file:

www.it-ebooks.info

CHAPTER 8: Introduction to Table Views

223

#import "BIDViewController.h"

@implementation BIDViewController

@synthesize listData;

.

.

.

- (void)viewDidLoad {

[super viewDidLoad];

// Do any additional setup after loading the view, typically from a nib.

NSArray *array = [[NSArray alloc] initWithObjects:@"Sleepy", @"Sneezy", @"Bashful", @"Happy", @"Doc", @"Grumpy", @"Dopey", @"Thorin", @"Dorin", @"Nori", @"Ori", @"Balin", @"Dwalin", @"Fili", @"Kili", @"Oin", @"Gloin", @"Bifur", @"Bofur", @"Bombur", nil];

self.listData = array;

}

.

.

.

Now, add the following line of code to the existing viewDidUnload method:

- (void)viewDidUnload { [super viewDidUnload];

//Release any retained subviews of the main view.

//e.g. self.myOutlet = nil;

self.listData = nil;

}

Finally, add the following code at the end of the file:

.

.

.

#pragma mark -

#pragma mark Table View Data Source Methods

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return [self.listData count];

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *SimpleTableIdentifier = @"SimpleTableIdentifier";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: SimpleTableIdentifier];

if (cell == nil) {

cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:SimpleTableIdentifier];

}

NSUInteger row = [indexPath row]; cell.textLabel.text = [listData objectAtIndex:row];

www.it-ebooks.info

224

CHAPTER 8: Introduction to Table Views

return cell;

}

@end

We added three methods to the controller. You should be comfortable with the first one, viewDidLoad, since we’ve done similar things in the past. We’re simply creating an array of data to pass to the table. In a real application, this array would likely come from another source, such as a text file, property list, or URL.

If you scroll down to the end, you can see we added two data source methods. The first one, tableView:numberOfRowsInSection:, is used by the table to ask how many rows are in a particular section. As you might expect, the default number of sections is one, and this method will be called to get the number of rows in the one section that makes up the list. We just return the number of items in our array.

The next method probably requires a little explanation, so let’s look at it more closely.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

This method is called by the table view when it needs to draw one of its rows. Notice that the second argument to this method is an NSIndexPath instance. This is the mechanism that table views use to wrap the section and row into a single object. To get the row or the section out of an NSIndexPath, you just call either its row method or its section method, both of which return an int.

The first parameter, tableView, is a reference to the table doing the asking. This allows us to create classes that act as a data source for multiple tables.

Next, we declare a static string instance.

static NSString *SimpleTableIdentifier = @"SimpleTableIdentifier";

This string will be used as a key to represent the type of our table cell. Our table will use only a single type of cell.

A table view can display only a few rows at a time on the iPhone’s small screen, but the table itself can conceivably hold considerably more. Remember that each row in the table is represented by an instance of UITableViewCell, a subclass of UIView, which means each row can contain subviews. With a large table, this could represent a huge amount of overhead if the table were to try to keep one table view cell instance for every row in the table, regardless of whether that row was currently being displayed. Fortunately, tables don’t work that way.

Instead, as table view cells scroll off the screen, they are placed into a queue of cells available to be reused. If the system runs low on memory, the table view will get rid of the cells in the queue. But as long as the system has some memory available for those cells, it will hold on to them in case you want to use them again.

Every time a table view cell rolls off the screen, there’s a pretty good chance that another one just rolled onto the screen on the other side. If that new row can just reuse one of the cells that has already rolled off the screen, the system can avoid the overhead

www.it-ebooks.info

CHAPTER 8: Introduction to Table Views

225

associated with constantly creating and releasing those views. To take advantage of this mechanism, we’ll ask the table view to give us a previously used cell of the specified type. Note that we’re making use of the NSString identifier we declared earlier. In effect, we’re asking for a reusable cell of type SimpleTableIdentifier.

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:

SimpleTableIdentifier];

Now, it’s completely possible that the table view won’t have any spare cells (when it’s being initially populated, for example), so we check cell after the call to see whether it’s nil. If it is, we manually create a new table view cell using that identifier string. At some point, we’ll inevitably reuse one of the cells we create here, so we need to make sure that we create it using SimpleTableIdentifier.

if (cell == nil) {

cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:SimpleTableIdentifier];

}

Curious about UITableViewCellStyleDefault? Hold that thought. We’ll get to it when we look at the table view cell styles.

We now have a table view cell that we can return for the table view to use. So, all we need to do is place whatever information we want displayed in this cell. Displaying text in a row of a table is a very common task, so the table view cell provides a UILabel property called textLabel that we can set in order to display strings. That just requires getting the correct string from our listData array and using it to set the cell’s textLabel.

To get the correct value, however, we need to know which row the table view is asking for. We get that information from the indexPath variable, like so:

NSUInteger row = [indexPath row];

We use the row number of the table to get the corresponding string from the array, assign it to the cell’s textLabel.text property, and then return the cell.

cell.textLabel.text = [listData objectAtIndex:row]; return cell;

}

That wasn’t so bad, was it? Compile and run your application, and you should see the array values displayed in a table view (see Figure 8–5).

www.it-ebooks.info

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]