2013-10-13 46 views
3

我有一個使用故事板的項目。我有一個靜態單元格和組風格的UITableView。UITableView - 節標題。如何更改文字?

我需要改變的一個部分,這取決於選擇在分段控制方面(在其他部分)

我已經找到了一些解決方案,表明你應該使用重寫此方法的部分文字:
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section

,並通過調用觸發更新:
[[self tableView]reloadSections:[NSIndexSet indexSetWithIndex:SectionToChange] withRowAnimation:UITableViewRowAnimationFade];

問題是,當我打電話reloadSections然後人l相關部分中的行和單元格被刪除。文本更新正確思想,但有這種不需要的副作用。

+0

可能的複製:http://stackoverflow.com/questions/10505708/how-to-set-the-uitableview-section-title-programmatically-iphone-ipad/10505982#10505982 – Alladinian

+0

由@Alladinian鏈接的問題有一個更乾淨的解決方案。只需重寫'numberOfSectionsInTableView:'將調用titleForSection,並且由於它是一個靜態tableview,因此您可以返回從故事板設計中知道的常量數 – GreatWiz

回答

0

如果你已經實現了這些功能,然後刪除它們應該解決您的問題:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
+0

我目前正在實現cellForRowAtIndexPath。刪除該功能不會改變結果。所有行和單元格在調用後被刪除: [[self tableView] reloadSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationFade]; 但節標題正確更改。 –

+0

numberOfRowsInSection方法呢?必須有一些底層控制方法告訴該部分重新加載數據後有0個單元。 –

+0

不,它不起作用。當我調用[[self tableView] reloadSections:[NSIndexSet indexSetWithIndex:SectionToChange] withRowAnimation:UITableViewRowAnimationFade];在問題部分,行和單元格消失,留下一個空的灰色空間。但節標題正確更改。 –

8

我想我找到了答案在這裏:Changing UITableView section header without tableView:titleForHeaderInSection

它可能不是很優雅,但它接縫的工作。

我可以通過調用觸發更新只與無的不必要的副作用節標題: [self.tableView headerViewForSection:1].textLabel.text = [self tableView:self.tableView titleForHeaderInSection:1];

因此唯一需要的就是要實現:

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section 
{ 
    if (section == 1){ 
     if (self.segmentX.selectedSegmentIndex == 0) // or some condition 
     return @"Header one"; 
     else 
     return @"Header two"; 
    } 
    return nil; 
} 
+1

這是一個非常好的答案。我有這個工作沒有問題,直到iOS 7.1.1。 –

+0

在iOS 8上,我得到了nil從headerViewForSection返回...爲了解決它,我只是緩存了我的委託創建的標題視圖,並引用了這些視圖。 – CMash

+0

如何將文本置於小寫。自動更改爲大寫。 – jose920405

-2
-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section 
{  if (section == 0) 
      { 
       lbl.text = @"abc"; 
      } 
     if (section == 2) 
      { 
       lbl.text = @"2ndsectionbeigns"; 
      } 
return headerview; 

}