Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

iOS 開發實作:為 UITableView 側滑操作擴充多個按鈕

編輯:關於 Android 程式設計

一、需求描述

系統預設的側滑操作只會出現一個「刪除」按鈕。本文要做的,是在同一個側滑菜單裡放入「刪除」、「置頂」、「更多」三個按鈕,讓列表互動更貼近實際產品的需要。

二、實現思路

滑動某個聯絡人或某則訊息時出現一排操作按鈕,這種互動現在很常見。在 iOS 8 之前,這一切都要自己動手實作;從 iOS 8 開始,系統已經把基礎能力內建好了,只要一個代理方法加上一個 UITableViewRowAction 類就能搞定。

關鍵在 UITableViewDelegate 新增的 tableView:editActionsForRowAtIndexPath: 方法,它的回傳值是一個陣列。我們在方法內部建立好各個按鈕,裝進陣列再回傳即可,而每個按鈕都由 UITableViewRowAction 來描述。

透過 UITableViewRowAction,我們可以設定按鈕的樣式、顯示文字、背景色,以及點擊後要執行的行為(行為寫在 handler 這個 Block 裡)。

在代理方法中建立多個按鈕並放入陣列時要注意順序:最先放進陣列的按鈕顯示在最右側,最後放進的顯示在最左側。

另外有一點容易踩坑:一旦自己設定了任何一個或多個按鈕,系統內建的刪除按鈕就會消失,需要自行補上。

三、程式碼實現

- (NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
    // 建立「刪除」按鈕
    UITableViewRowAction *deleteRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@"刪除" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
        NSLog(@"點擊了「刪除」");
        // 1. 更新資料來源
        // 2. 更新 UI
        // [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
    }];

    // 建立「置頂」按鈕
    UITableViewRowAction *topRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"置頂" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
        NSLog(@"點擊了「置頂」");
        // 1. 更新資料來源
        // 2. 更新 UI
        // NSIndexPath *firstIndexPath = [NSIndexPath indexPathForRow:0 inSection:indexPath.section];
        // [tableView moveRowAtIndexPath:indexPath toIndexPath:firstIndexPath];
    }];
    topRowAction.backgroundColor = [UIColor blueColor];

    // 建立「更多」按鈕
    UITableViewRowAction *moreRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"更多" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
        NSLog(@"點擊了「更多」");
        [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationMiddle];
    }];
    moreRowAction.backgroundEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleDark];

    // 依序放入陣列回傳,越前面越靠右
    return @[deleteRowAction, topRowAction, moreRowAction];
}

三個按鈕的樣式各有差異:「刪除」使用 Destructive 帶出系統紅色、「置頂」自訂藍色、「更多」則加上毛玻璃模糊效果,視覺層次就出來了。

延伸閱讀

· 詳解 iOS 開發中 UITableView 頂部留白的多種處理方式

· iOS 中讓 UITableView 滾動到指定位置的實作

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved