UITableViewDataSource協議,uitableview
前言:
在iOS開發中,表視圖UITableView 是我們做UI介面設計時的重要視圖。
那麼,使用表視圖UITableView 需要遵守哪些協議呢?
<UITableViewDataSource,UITableViewDelegate>
UITableViewDataSource 表視圖資料來源協議,用來控製表視圖的顯示內容;
UITableViewDelegate 表視圖協議,用來控製表視圖的顯示以及每個cell的高度和每個分區的頭尾高度等;
本文先學習UITableViewDataSource協議。
UITableViewDataSource協議有哪些方法呢?
首先,必須要實現的方法:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
這個方法用來設定tableView的每個分組的行數;
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
這個方法用來返回cell,就是用來控制每一行返回的內容;
以上兩個方法是必須實現的;
其他可選擇的呢?
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView;
設定tableView裡面有幾個分區,如果不寫預設為1;
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section;
設定分區頭的內容,傳回值是NSString類型;
- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section;
同理,這個方法是設定分區尾的內容,傳回值是NSString類型;
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath;
這個方法是用來控制Cell是否可以編輯,如果沒有實現,所有行被認為是可編輯的;
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath;
這個方法是用來控制Cell是否可以移動,只有實現了,才可以移動;
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView;
返回每個分區的標題;
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index;
告訴tableView,哪一行和哪一個分組標題對應;
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath;
在編輯結束cell的時候,儲存修改;
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath;
根據行數交換cell;
以上就是所有的UITableViewDataSource協議的方法;