UITableView中的部分

时间:2014-04-07 14:51:02

标签: ios uitableview

我一直在努力研究如何将节标题添加到我的UITableView,几天和几天,尽我所能地研究,阅读它接缝数百页,是否有人至少指出了我正确的方向,好吗?

我有一个数组:

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

这是来自以下132的提要:

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

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

等等......

我正在寻找:

A
Almonds
Apples
B
Bananas
Blackcurrants...

共有27个部分。

2 个答案:

答案 0 :(得分:1)

如果您只想要节标题标题,可以使用UITableViewDataSource方法:

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

或者您可以使用UITableViewDelegate方法将自定义视图设置为标题:

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

实现这些的控制器需要是表视图的委托/数据源。

答案 1 :(得分:0)

对于字母排名,请尝试以下内容:

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

  return [alphabet objectAtIndex:section];
}

此处字母表是在ViewDidLoad中声明的NSArray。参考(link

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

对于自定义:

- (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 @"";
}

对于文本的对齐尝试方法如下。

- (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;
  }