您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

iOS:UITableViewDataSource 與 UITableViewDelegate 常用方法速查

編輯:iOS 相關資訊

本文把 UITableView 兩個核心協定中最常使用的方法整理成速查表,方便開發時快速對照。

一、UITableViewDataSource 常用方法

// 1. 右側索引值
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView

// 2. 分組標題
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section

// 3. 分組個數
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView

// 4. 列數
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

5. 建立 cell(重用機制):

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"reuse";           // 建立重用標識符
    AddressBookCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {                                       // 若無可重用者才建立
        cell = [[[AddressBookCell alloc] initWithStyle:UITableViewCellStyleDefault
                                      reuseIdentifier:identifier] autorelease];
    }
    return cell;
}
// 6. 設定列是否可編輯
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

// 7. 點擊 edit 按鈕時觸發
- (void)setEditing:(BOOL)editing animated:(BOOL)animated

// 8. 提交編輯操作時觸發
- (void)tableView:(UITableView *)tableView
    commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
     forRowAtIndexPath:(NSIndexPath *)indexPath

// 9. 是否允許移動
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

// 10. 提交移動之後觸發
- (void)tableView:(UITableView *)tableView
    moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath
           toIndexPath:(NSIndexPath *)destinationIndexPath

二、UITableViewDelegate 常用方法

// 1. 設定列高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 55;
}

// 2. 選中 cell 時觸發
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

// 3. cell 的編輯樣式(插入/刪除)
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView
           editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath

// 4. 點擊編輯按鈕時顯示的文字(如「刪除」)
- (NSString *)tableView:(UITableView *)tableView
    titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"刪除";
}

// 5. 設定 cell 移動的目標位置
- (NSIndexPath *)tableView:(UITableView *)tableView
    targetIndexPathForMoveFromRowAtIndexPath:(NSIndexPath *)sourceIndexPath
           toProposedIndexPath:(NSIndexPath *)proposedDestinationIndexPath
  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved