iOS开发之-Table View-Creating and Configuring

Creating and Configuring a Table View




1. The client creates aUITableView instance in a certain frame and style. It can do this either programmatically or in Interface Builder. The frame is usually set to the screen frame, minus the height of the status bar or, in a navigation-based application, to the screen frame minus the heights of the status bar and the navigation bar. The client may also set global properties of the table view at this point, such as its autoresizing behavior or a global row height.


Recommendations for Creating and Configuring Table Views

If the view to be managed is a composite view in which a table view is one of multiple subviews, you must use a custom subclass ofUIViewController to manage the table view (and other views). Do not use aUITableViewController object because this controller class sizes the table view to fill the screen between the navigation bar and the tab bar (if either are present).


Creating a Table View Programmatically

Listing 4-2  Adopting the data source and delegate protocols
@interface RootViewController : UIViewController  <UITableViewDelegate, UITableViewDataSource> {

    NSArray *timeZoneNames;

}

@property (nonatomic, retain) NSArray *timeZoneNames;

@end

Listing 4-3  Creating a table view
- (void)loadView

{

    UITableView *tableView = [[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]

                                  style:UITableViewStylePlain];

    tableView.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth;

    tableView.delegate = self;

    tableView.dataSource = self;

    [tableView reloadData];

    self.view = tableView;

    [tableView release];

}


Populating the Table View With Data

Listing 4-4  Populating a table view with data
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return [regions count];

}
 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    // Number of rows is the number of time zones in the region for the specified section.

    Region *region = [regions objectAtIndex:section];

    return [region.timeZoneWrappers count];

}
 

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {

    // The header for the section is the region name -- get this from the region at the section index.

    Region *region = [regions objectAtIndex:section];

    return [region name];

}


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

    static NSString *MyIdentifier = @"MyIdentifier";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];

    if (cell == nil) {

        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyIdentifier] autorelease];

    }

    Region *region = [regions objectAtIndex:indexPath.section];

    TimeZoneWrapper *timeZoneWrapper = [region.timeZoneWrappers objectAtIndex:indexPath.row];

    cell.textLabel.text = timeZoneWrapper.localeName;

    return cell;

}

Populating an Indexed List

An indexed list is a table view in the plain style that is specially configured through threeUITableViewDataSource methods:sectionIndexTitlesForTableView:, tableView:titleForHeaderInSection:, and tableView:sectionForSectionIndexTitle:atIndex:


You might find it convenient to define a custommodel class whose instances represent the rows in the table view. These model objects not only return a string value but define a property that holds the index of the section array to which the object is assigned. 


Listing 4-5  Defining the model-object interface
@interface State : NSObject {
    NSString *name;
    NSString *capitol;
    NSString *population;
    NSInteger sectionNumber;
}
 
@property(nonatomic,copy) NSString *name;
@property(nonatomic,copy) NSString *capitol;
@property(nonatomic,copy) NSString *population;
@property NSInteger sectionNumber;
@end



Listing 4-6  Loading the table-view data and initializing the model objects
- (void)viewDidLoad {
    [super viewDidLoad];
    UILocalizedIndexedCollation *theCollation = [UILocalizedIndexedCollation currentCollation];
    self.states = [NSMutableArray arrayWithCapacity:1];
 
    NSString *thePath = [[NSBundle mainBundle] pathForResource:@"States" ofType:@"plist"];
    NSArray *tempArray;
    NSMutableArray *statesTemp;
    if (thePath && (tempArray = [NSArray arrayWithContentsOfFile:thePath]) ) {
        statesTemp = [NSMutableArray arrayWithCapacity:1];
        for (NSDictionary *stateDict in tempArray) {
            State *aState = [[State alloc] init];
            aState.name = [stateDict objectForKey:@"Name"];
            aState.population = [stateDict objectForKey:@"Population"];
            aState.capitol = [stateDict objectForKey:@"Capitol"];
            [statesTemp addObject:aState];
            [aState release];
        }
    } else  {
        return;
    }

 // viewDidLoad continued...
    // (1)
    for (State *theState in statesTemp) {
        NSInteger sect = [theCollation sectionForObject:theState collationStringSelector:@selector(name)];
        theState.sectionNumber = sect;
    }
    // (2)
    NSInteger highSection = [[theCollation sectionTitles] count];
    NSMutableArray *sectionArrays = [NSMutableArray arrayWithCapacity:highSection];
    for (int i=0; i<=highSection; i++) {
        NSMutableArray *sectionArray = [NSMutableArray arrayWithCapacity:1];
        [sectionArrays addObject:sectionArray];
    }
    // (3)
    for (State *theState in statesTemp) {
        [(NSMutableArray *)[sectionArrays objectAtIndex:theState.sectionNumber] addObject:theState];
    }
    // (4)
    for (NSMutableArray *sectionArray in sectionArrays) {
        NSArray *sortedSection = [theCollation sortedArrayFromArray:sectionArray
            collationStringSelector:@selector(name)];
        [self.states addObject:sortedSection];
    }
} // end of viewDidLoad



- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    return [[UILocalizedIndexedCollation currentCollation] sectionIndexTitles];
}
 
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    if ([[self.states objectAtIndex:section] count] > 0) {
        return [[[UILocalizedIndexedCollation currentCollation] sectionTitles] objectAtIndex:section];
    }
    return nil;
}
 
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
    return [[UILocalizedIndexedCollation currentCollation] sectionForSectionIndexTitleAtIndex:index];
}

Listing 4-9  Populating the rows of an indexed list
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return [self.states count];
}
 
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [[self.states objectAtIndex:section] count];
}
 
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"StateCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                   reuseIdentifier:CellIdentifier] autorelease];
    }
    State *stateObj = [[self.states objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
    cell.textLabel.text = stateObj.name;
    return cell;
}


Optional Table-View Configurations


Listing 4-10  Adding a title to the table view
- (void)loadView
{
    [super loadView];
 
    CGRect titleRect = CGRectMake(0, 0, 300, 40);
    UILabel *tableTitle = [[UILabel alloc] initWithFrame:titleRect];
    tableTitle.textColor = [UIColor blueColor];
    tableTitle.backgroundColor = [self.tableView backgroundColor];
    tableTitle.opaque = YES;
    tableTitle.font = [UIFont boldSystemFontOfSize:18];
    tableTitle.text = [curTrail objectForKey:@"Name"];
    self.tableView.tableHeaderView = tableTitle;
    [self.tableView reloadData];
    [tableTitle release];
}

Listing 4-12  Custom indentation of a row
- (NSInteger)tableView:(UITableView *)tableView indentationLevelForRowAtIndexPath:(NSIndexPath *)indexPath {
    if ( indexPath.section==TRAIL_MAP_SECTION && indexPath.row==0 ) {
        return 2;
    }
    return 1;
}

Listing 4-13  Varying row height
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat result;
 
    switch ([indexPath row])
    {
        case 0:
        {
            result = kUIRowHeight;
            break;
        }
        case 1:
        {
            result = kUIRowLabelHeight;
            break;
        }
    }
    return result;
}


UILocalizedIndexedCollation Class

To prepare the data for a section index, your table-view controller creates a indexed-collation object and then, for each model object that is to be indexed, callssectionForObject:collationStringSelector:. This method determines the section in which each of these objects should appear and returns an integer that identifies the section. The table-view controller then puts each object in a local array for its section. For each section array, the controller calls the sortedArrayFromArray:collationStringSelector: method to sort all of the objects in the section. The indexed-collation object is now the data store that the table-view controller uses to provide section-index data to the table view, as illustrated in Listing 1.


Listing 1  Data source using indexed-collation object to provide data to table view
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return [[[UILocalizedIndexedCollation currentCollation] sectionTitles] objectAtIndex:section];
}
 
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    return [[UILocalizedIndexedCollation currentCollation] sectionIndexTitles];
}
 
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
    return [[UILocalizedIndexedCollation currentCollation] sectionForSectionIndexTitleAtIndex:index];
}

example

- (void)setUpData
{
	NSMutableArray *timeZones = [[NSMutableArray alloc] init];
	NSArray *timeZoneNames = [NSTimeZone knownTimeZoneNames];
	UILocalizedIndexedCollation *collation = [UILocalizedIndexedCollation currentCollation];
	
	for (NSString *timeZoneName in timeZoneNames){
		NSArray *nameComponents = [timeZoneName componentsSeparatedByString:@"/"];
		NSString *regionName = [nameComponents objectAtIndex:0];
		NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:regionName];
		
		TimeZoneWrapper *timeZoneWrapper = [[TimeZoneWrapper alloc] initWithTimeZone:timeZone nameComponents:nameComponents];
		[timeZones addObject:timeZoneWrapper];
		[timeZoneWrapper release];
	}
	
	for (TimeZoneWrapper *timeZoneWrapper in timeZones){
		NSInteger section = [collation sectionForObject:timeZoneWrapper collationStringSelector:@selector(localeName)];
		timeZoneWrapper.sectionNumber = section;
	}
	
	NSInteger highSection = collation.sectionTitles.count;
	NSMutableArray *tempSectionArrays = [[NSMutableArray alloc] initWithCapacity:highSection];
	for (int i = 0; i < highSection; i++){
		NSMutableArray *sectionArray = [[NSMutableArray alloc] init];
		[tempSectionArrays addObject:sectionArray];
		[sectionArray release];
	}
	
	for (TimeZoneWrapper *timeZoneWrapper in timeZones){
		NSMutableArray *sectionArray = [tempSectionArrays objectAtIndex:timeZoneWrapper.sectionNumber];
		[sectionArray addObject:timeZoneWrapper];
	}
	
	for (NSMutableArray *sectionArray in tempSectionArrays){
		[collation sortedArrayFromArray:sectionArray collationStringSelector:@selector(localeName)];
	}
	
	self.sectionArrays = tempSectionArrays;
	self.timeZoneWrappers = timeZones;
	
	[tempSectionArrays release];
	[timeZones release];
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值