2025-05-24

相信做過iOS的程序員,最熟悉的控件一定少不瞭UITableView,最常用的控件也一定少不瞭UITableView!

 

今天分享一下自己對UITableView的實現大體思路,和整理出來的學習筆記!

 

1.UITableView裡的結構圖                       

 

 

 

 

 

2.UITableView數據展示的條件                      

 

1> UITableView的所有數據都是由數據源(dataSource)提供的,所以要想在UITableView展示數據,必須設置UITableView的dataSource數據源對象

 

2> 要想當UITableView的dataSource對象,必須遵守UITableViewDataSource協議,實現相應的數據源方法

 

3> 當UITableView想要展示數據的時候,就會給數據源發送消息(調用數據源方法),UITableView會根據方法返回值決定展示怎樣的數據

 

 

 

3.數據展示的過程                             

 

數據顯示,三步走

 

1> 先調用數據源的

 

– (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView

 

得知一共有多少組

 

 

 

2> 然後調用數據源的

 

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

 

得知第section組一共有多少行

 

 

 

3> 然後調用數據源的

 

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

 

得知第indexPath.section組 第indexPath.row 行顯示怎樣的cell(顯示什麼內容)

 

 

 

4.開發中經常用到的UITableView數據源方法               

 

1> 一共有多少組

 

– (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView

 

 

 

@required  2.3 是必須實現

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;

 

 

 

5.開發中經常用到的UITableView代理方法               

 

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

選中瞭UITableView的某一行

 

2.- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

某一行的高度

 

3.- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section

第section分區頭部的高度

 

4.- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section

第section分區尾部的高度

 

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

 

第section分區頭部顯示的視圖

 

6.- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section

第section分區尾部顯示的視圖

 

7.- (NSInteger)tableView:(UITableView *)tableView indentationLevelForRowAtIndexPath:(NSIndexPath *)indexPath

設置每一行的等級縮進(數字越小,等級越高)

 

 

 

6.tableView刷新數據的方式                      

 

 1> 修改模型數據

 

 2> 刷新表格

 

– reloadData

 

整體刷新(每一行都會刷新)

 

 – (void)reloadRowsAtIndexPaths:(NSArray *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation

 

局部刷新

 

 

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *