2017-02-09 90 views
1

我有一個UITableViewController,它的表視圖具有靜態單元格,在故事板中定義。動態更改靜態單元格上的節標題文本

我的表格視圖有兩個部分。第一個有兩個單元,第二個有三個單元。第二部分的標題中也有文字。

我想要做的是當用戶點擊第一部分中的第一個或第二個單元格時,更新第二個部分的標題文本。動態地使用動態內容(例如,在點擊單元格的那一刻顯示日期和時間)。

我嘗試了很多東西,但viewForHeaderSection只被調用一次。

我註冊了

tableView.registerClass(TableSectionHeader.self, forHeaderFooterViewReuseIdentifier: "secondSectionCell") 

頁眉節電池在哪裏TableSectionHeader很簡單:

class TableSectionHeader: UITableViewHeaderFooterView { } 

我就能夠動態地設置節頭,就像這樣:

override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { 
     if section == 1 { 
      if let cell = tableView.dequeueReusableHeaderFooterViewWithIdentifier("secondSectionCell") { 
       cell.textLabel?.text = "hello world" 
       return cell 
      } 

     } 

     return nil 
    } 

我也實施了以下重寫,因爲有些人建議t當執行viewForHeaderInSection時,還需要:

override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { 
    return 40.0 
} 

即使如此。 viewForHeaderInSection只被調用一次。

我能夠以某種方式動態刷新部分標題文本,如上所述?

+1

你不能這樣做它。沒有這方面的官方文件。你需要做自定義方法,如:http://stackoverflow.com/questions/23501952/refresh-only-the-custom-header-views-in-a-uitableview,但是,我強烈建議你離開節標題單獨使用細胞,而不是每個部分的第一個細胞。除非你想做一些你需要的粘性標題或其他東西。 – 2017-02-09 03:18:18

+0

@Sneak我喜歡你的建議。可能是最簡單的方法。唯一的事情是擺弄桌面視圖來處理分隔單元格的線條,以及它們如何從tableview的左邊緣插入。 – dbarros

+0

tableView.reloadSections將重新加載頁眉(和頁腳)以及該部分的內容 – Dale

回答

0

實際上,您可以使用傳統的表格視圖方式輕鬆實現此目的。

即使是靜態的UITableView,在您的數據源視圖控制器,你仍然可以實現- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section

那麼,如何動態更新的標題?爲此視圖控制器創建一個屬性,如NSString *titleForSecondSection。每當用戶點擊第一部分中的單元格時,只需要在回調中更新此屬性- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

最後一步是在修改titleForSecondSection屬性後調用[self.tableView reload]。或者如果您不想重新加載整個表格視圖,只需撥打- (void)reloadSections:(NSIndexSet *)sections withRowAnimation:(UITableViewRowAnimation)animation

要清楚,在您的- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section中,對於不需要更改標題的部分,只需返回一個靜態字符串即可。對於需要更改標題的部分,返回您創建的動態屬性。

+0

對不起,我只注意到你在使用Swift。應該在Swift中發佈。但它是一樣的想法。希望能幫助到你。 :) – Elvin

0

viewForHeaderInSection只會在tableview被重新加載時調用。所以假設你不想重新加載整個tableview,你可能需要直接更改標籤的內容。 僞代碼,如:

var label_first_section_header //as global variable 

然後在viewForHeaderInSection只需將它指向標籤

if section == 1 { 
    if let cell = tableView.dequeueReusableHeaderFooterViewWithIdentifier("secondSectionCell") { 
     cell.textLabel?.text = "hello world" 
     label_first_section_header = cell.textLabel 
     return cell 
    } 
} 

那麼你就可以動態地更改文本,只要你想,例如在didSelectRowAtIndexPath方法