UITableView 簡單總結

在UITableView 初始化的時候,可以選擇要顯示什麼樣式的表格,它的 style 參數是個枚舉類型,可以自行選擇要顯示的樣式。Group型是分組顯示,Plain是一般列表型。


1. 數據展示的條件

  • UITableView 的所有數據都是由數據源(dataSource)來提供,所以要想再UITableView中展示數據,必須先設置UITableView 的dataSource數據源對象。
  • 要想作爲UITableView的dataSource對象,它必須遵守UITableViewDataSource協議,然後實現相應的數據源方法,才能使數據顯示在 UITableView 中。
  • 當UITableView想要展示數據的時候,就會給數據源發送消息(即調用數據源的相應方法),UITableView 會根據方法返回值來決定顯示什麼數據。


2. 數據展示的過程

1)先調用數據源中的以下方法來得知要顯示多少組數據:

- (NSInteger)numberOfSectionsInTableView: (UITableView *)tableView


2)調用數據源的以下方法來獲知第section組中一共有多少行:

- (NSInteger)tableView: (UITableView *)tableView numberOfRowsInSection: (NSInteger)section


3)調用數據源的以下方法來獲知第 indexPath.section 組中的第 indexPath.row 行要顯示怎樣的cell(即什麼內容)

- (UITableViewCell *)tableView: (UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath


3. 常見數據源及代理方法

1)一共多少組:

- (NSInteger)numberOfSectionsInTableView: (UITableView *)tableView


2)第section組中一共有多少行:

- (NSInteger)tableView: (UITableView *)tableView numberOfRowsInSection: (NSInteger)section


3)第 indexPath.section 組中的第 indexPath.row 行要顯示怎樣的cell(即什麼內容)

- (UITableViewCell *)tableView: (UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath


4)第section組要顯示怎樣的頭部標題

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


5)第section組要顯示怎樣的尾部信息(一般是解釋性信息)

- (NSString *)tableView: (UITableView *)tableView titleForFooterInSection: (NSInteger)section;


6) 返回表格右邊的索引條,用以快速尋找某項數據,它的順序是根據表格中的數據組的順序來一一對應

- (NSArray *)sectionIndexTitlesForTableView: (UITableView *)tableView


7) 監聽列表項點擊事件

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath


4. 數據刷新

    //這個方法一般用以刷新列表中大量的數據
    // [_tableView reloadData];
        
    // 這一方法用以刷新少量目標行
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:0];
    [_tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationRight];



5. 數據加載優化

#pragma mark 返回每一行的cell
#pragma mark 每當有一個cell進入視野範圍內就會調用
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *ID = @"C1";   
    // 1.從緩存池中取出可循環利用的cell
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    // 2.如果緩存池中沒有可循環利用的cell
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
    }
    
    cell.textLabel.text = [NSString stringWithFormat:@"第%d行數據", indexPath.row];
    
    return cell;
}


發佈了35 篇原創文章 · 獲贊 0 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章