您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

UITableView 實用小技巧整理

編輯:iOS 開發綜合

UITableView 是 iOS 開發中出現頻率最高的元件之一,以下把幾個常用的列舉型別與實務技巧整理在一起。

三個關鍵列舉

UITableViewCellSelectionStyle:控制 cell 被點選時的高亮樣式,有 None(不高亮)、Blue(藍底)、Gray(灰底)三種。

UITableViewCellAccessoryType:控制 cell 右側的附屬檢視。None 不顯示;DisclosureIndicator 是灰色箭頭、不可點擊;DetailDisclosureButton 是藍色按鈕加箭頭、可點擊;Checkmark 則是勾選標記。

UITableViewCellSeparatorStyle:控制分隔線樣式,None 為不顯示,SingleLine 為單線,若要改顏色則另外設定 separatorColor。

1. 返回時停留在原本的位置

點擊 cell 進入下一頁後再返回,列表往往會被滾回最頂端,體驗很差。解法是記下點擊的 indexPath,在 viewWillAppear: 時重新選中該列:

NSIndexPath *ip = [NSIndexPath indexPathForRow:row inSection:section];
[topicsTable selectRowAtIndexPath:ip animated:YES scrollPosition:UITableViewScrollPositionNone];

2. 點選後立刻取消高亮

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

3. 禁止某些列被點擊

實作 willSelectRowAtIndexPath: 並回傳 nil,就能攔下特定列:

- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([indexPath row] == 0) return nil;   // 第一列不可選
    return indexPath;
}

4. 控制左滑是否出現刪除鈕

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return ([indexPath row] != 0);   // 第一列不允許刪除
}

5. 處理編輯狀態的提交

- (void)tableView:(UITableView *)tableView
commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // 從資料來源移除資料,再 reload 或 deleteRowsAtIndexPaths
    }
}

6. 右側索引列

實作以下方法即可在列表右側出現 A、B、C 的索引條,適合聯絡人這類大量資料:

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    return @[@"A", @"B", @"C", @"Z"];
}

7. Section 標題

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    return @"Section Title";
}

注意:原方法名若拼成 titleForHeardInSection 是不會被呼叫的,正確拼法是 titleForHeaderInSection,這也是新手常踩的雷。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved