2013-01-08 121 views
3

我有一个静态tableView与一些自定义单元格。我想要做的是以编程方式更改节标题。据我所知,因为单元格是静态的,所以我不能使用像cellForRowAtIndexPath等方法,所以我的问题是,它可能会改变它们。编辑静态tableView单元格部分

self.tableView.section1.text = @"title1"; // something like this? 

我试图创建节的一个IBOutlet,但我得到了以下错误:

Unknown type name 'UITableViewSection': did you mean 'UITableViewStyle?' 

什么我可以做的是编辑单元格的内容,而不是标题。

谢谢!

回答

6

使用viewForHeaderInSection方法。

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


     UILabel *label1 = [[UILabel alloc] init]; 
     label1.frame = CGRectMake(0, 0, 190, 20); 
     label1.textColor = [UIColor blackColor]; 
     // label1.font = [UIFont fontWithName:@"Helvetica Bold" size:16]; 
     [label1 setFont:[UIFont fontWithName:@"Arial-BoldMT" size:14]]; 
     label1.textAlignment = UITextAlignmentCenter; 

     label1.text =[NSString stringWithFormat:@"Title %d",section]; 
// If your title are inside an Array then Use Below Code 

     label1.text =[titleArray objectAtindex:section]; 

     label1.textColor = [UIColor whiteColor]; 
     label1.backgroundColor = [UIColor clearColor]; 




UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 30)]; 
    [view addSubview:label1]; 

    view.backgroundColor = [UIColor orangeColor]; 
     return view; 

    } 

如果您想使用titleForHeaderInSection,请使用下面的代码。

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

return [NSString stringWithFormat:@"Title %d",section]; 
// If your title are inside an Array then Use Below Code 

     return [titleArray objectAtindex:section]; 
} 
+0

非常感谢你,这完美的作品! – Linus

3

可以使用的UITableViewDelegate协议方法tableview:titleForHeaderInSection:

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

    NSString *sectionTitle = @""; 

    switch (section) { 

     case 0: sectionTitle = @"Section 1"; break; 
     case 1: sectionTitle = @"Section 2"; break; 
     case 2: sectionTitle = @"Section 3"; break; 

     default: 
      break; 
    } 

    return sectionTitle; 
} 

确保你宣布你<UITableViewDelegate>在您的.h文件中:

@interface SettingsViewController : UITableViewController <UITableViewDelegate> { 

} 
+0

只要在视图加载之前设置了节标题,就可以很好地工作。不过,我希望能够更改表格标题,以响应表格上的用户操作。任何方式来强制表重新加载或反映这些更改(假设我将sectionTitle设置为更改的本地属性值)? – Nick

+1

想通了:更容易做到这一点:'[self.tableView headerViewForSection:1] .textLabel.text = @“blah”;'Via http://stackoverflow.com/a/17959411/1304462 – Nick

1

如果您需要更改头时视图显示为'live',您可以这样做:

int sectionNumber = 0; 
[self.tableView headerViewForSection:sectionNumber].textLabel.text = @"Foo Bar"; 

但是这样做似乎并没有改变标签框的大小。我只是提前将我的身材做得更大。 More details here.

相关问题