简体   繁体   中英

Section in a UITableView

I have been trying to work out how to add section headers to my UITableView, for days and days, researching as best I can, reading it seams hundreds of pages, can someone at least point me in the right direction, please?

I have an array:

  recipes = [NSArray arrayWithObjects:recipe1, recipe2, recipe3, recipe4, nil];

That is feed from 132 of the below:

Recipe *recipe1 = [Recipe new];
recipe1.name = @"Almonds";
recipe1.image = @"almonds.jpg";

Recipe *recipe2 = [Recipe new];
recipe2.name = @"Apples";
recipe2.image = @"apples.jpg";

And so on...

And am looking for:

A
Almonds
Apples
B
Bananas
Blackcurrants...

There are 27 sections.

if you just want section header title, you can use UITableViewDataSource method:

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

Or you can set your custom view as header using UITableViewDelegate method:

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section

The controller implementing these, needs to be the delegate/datasource of your table view.

For alphabets exclusively, Try something like:

- (NSString *)tableView:(UITableView *)aTableView titleForHeaderInSection:(NSInteger)section
{
  if ([aTableView numberOfRowsInSection:section] == 0) return nil;

  return [alphabet objectAtIndex:section];
}

Here alphabet is NSArray declared in ViewDidLoad. Reference( link )

alphabet = [[NSArray alloc]initWithObjects:@"A",@"B",@"C",...,@"Z",nil];

For custom:

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
 if (section==0) {
    return @"";
} else if (section==1) {
    return @"Actions";
} else if (section==2) {
    return @"Attached To";
}

return @"";
}

And for alignment of text try method below.

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
 UILabel * sectionHeader = [[[UILabel alloc] initWithFrame:CGRectZero] autorelease];
 sectionHeader.backgroundColor = [UIColor clearColor];
 sectionHeader.textAlignment = UITextAlignmentCenter;
 sectionHeader.font = [UIFont boldSystemFontOfSize:10];
 sectionHeader.textColor = [UIColor whiteColor];

 switch(section) {
    case 0:sectionHeader.text = @"TITLE ONE"; break;
    case 1:sectionHeader.text = @"TITLE TWO"; break;
    default:sectionHeader.text = @"TITLE OTHER"; break;
 }  
   return sectionHeader;
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM