您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 使用技巧 >> iOS 7 技巧

Swift 實作 UITableView 多選:三種寫法與批次刪除

編輯:iOS 7 技巧

UITableView 本身內建了多選能力,不必引入任何第三方庫。實務上常見有三種做法,差別在於「要不要自己維護選中狀態」以及「是否處於編輯模式」。以下逐一拆解。

做法一:自備陣列記錄索引(非編輯狀態)

這是最直觀的寫法。宣告一個 [Int] 存索引:

  • 點擊某列 → 索引加入陣列,並在 cell 尾端顯示打勾。
  • 再點同一列 → 從陣列移除,取消打勾。
  • 按下導航列「確定」→ 印出所有選中的索引與對應文字。

要注意 cell 會被重複使用,所以務必在 cellForRowAtIndexPath 裡「每次都重設」accessoryType,否則滑動後勾選狀態會錯亂。

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    var items:[String] = ["條目1","條目2","條目3","條目4","條目5"]

    //存儲選中單元格的索引
    var selectedIndexs = [Int]()

    var tableView:UITableView?

    override func viewDidLoad() {
        super.viewDidLoad()

        //創建表視圖
        self.tableView = UITableView(frame: self.view.frame, style:UITableViewStyle.Plain)
        self.tableView!.delegate = self
        self.tableView!.dataSource = self
        //創建一個重用的單元格
        self.tableView!.registerClass(UITableViewCell.self,
                                      forCellReuseIdentifier: "SwiftCell")
        self.view.addSubview(self.tableView!)
    }

    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1;
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.items.count
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath)
        -> UITableViewCell
    {
        let identify:String = "SwiftCell"
        let cell = tableView.dequeueReusableCellWithIdentifier(identify,
                                                              forIndexPath: indexPath) as UITableViewCell

        cell.textLabel?.text = self.items[indexPath.row]

        //判斷是否選中(選中單元格尾部打勾)
        if selectedIndexs.contains(indexPath.row) {
            cell.accessoryType = UITableViewCellAccessoryType.Checkmark
        } else {
            cell.accessoryType = UITableViewCellAccessoryType.None
        }

        return cell
    }

    // UITableViewDelegate 方法,處理列表項的選中事件
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){
        //判斷該行原先是否選中
        if let index = selectedIndexs.indexOf(indexPath.row){
            selectedIndexs.removeAtIndex(index) //原來選中的取消選中
        }else{
            selectedIndexs.append(indexPath.row) //原來沒選中的就選中
        }

        //刷新該行
        self.tableView?.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
    }

    //確定按鈕點擊
    @IBAction func btnClick(sender: AnyObject) {
        print("選中項的索引為:", selectedIndexs)
        print("選中項的值為:")
        for index in selectedIndexs {
            print(items[index])
        }
    }
}

做法二:allowsMultipleSelection = true(非編輯狀態)

上面那個範例本質上表格仍是單選,只是我們用陣列「假裝」成多選。更省事的方式是直接把 tableView 的多選屬性打開,選中集合交給系統維護,透過 indexPathsForSelectedRows 就能一次取回。

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    var items:[String] = ["條目1","條目2","條目3","條目4","條目5"]

    var tableView:UITableView?

    override func viewDidLoad() {
        super.viewDidLoad()

        self.tableView = UITableView(frame: self.view.frame, style:UITableViewStyle.Plain)
        self.tableView!.delegate = self
        self.tableView!.dataSource = self
        self.tableView!.registerClass(UITableViewCell.self,
                                      forCellReuseIdentifier: "SwiftCell")
        self.view.addSubview(self.tableView!)

        //設置允許單元格多選
        self.tableView!.allowsMultipleSelection = true
    }

    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1;
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.items.count
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath)
        -> UITableViewCell
    {
        let identify:String = "SwiftCell"
        let cell = tableView.dequeueReusableCellWithIdentifier(identify,
                                                              forIndexPath: indexPath) as UITableViewCell
        cell.textLabel?.text = self.items[indexPath.row]
        return cell
    }

    //處理列表項的選中事件
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){
        let cell = self.tableView?.cellForRowAtIndexPath(indexPath)
        cell?.accessoryType = .Checkmark
    }

    //處理列表項的取消選中事件
    func tableView(tableView: UITableView,
                   didDeselectRowAtIndexPath indexPath: NSIndexPath) {
        let cell = self.tableView?.cellForRowAtIndexPath(indexPath)
        cell?.accessoryType = .None
    }

    //確定按鈕點擊
    @IBAction func btnClick(sender: AnyObject) {
        var selectedIndexs = [Int]()

        if let selectedItems = tableView!.indexPathsForSelectedRows {
            for indexPath in selectedItems {
                selectedIndexs.append(indexPath.row)
            }
        }

        print("選中項的索引為:", selectedIndexs)
        print("選中項的值為:")
        for index in selectedIndexs {
            print(items[index])
        }
    }
}

這裡有個容易忽略的細節:取消選但要另外實作 didDeselectRowAtIndexPath 把勾拿掉,系統不會幫你處理 accessory 的視覺狀態。

做法三:allowsMultipleSelectionDuringEditing = true(編輯狀態下多選)

這種互動最接近 iOS 系統 App 的體驗:平時不能多選,長按表格進入編輯模式後,cell 左側會出現選擇框,勾選完成再按「刪除」批次移除。

  • 長按手势(minimumPressDuration 設為 1.0)用來切換 editing 狀態。
  • 進入編輯後開啟多選,勾選方塊由系統繪製。
  • 刪除時先取出索引,呼叫 Array 擴充的 removeAtIndexes,再 reloadData 並退出編輯狀態。
import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource,
                      UIGestureRecognizerDelegate {

    var items:[String] = ["條目1","條目2","條目3","條目4","條目5"]

    var tableView:UITableView?

    override func viewDidLoad() {
        super.viewDidLoad()

        //創建表視圖
        self.tableView = UITableView(frame: self.view.frame, style:UITableViewStyle.Plain)
        self.tableView!.delegate = self
        self.tableView!.dataSource = self
        self.tableView!.registerClass(UITableViewCell.self,
                                      forCellReuseIdentifier: "SwiftCell")
        self.view.addSubview(self.tableView!)

        //表格在編輯狀態下允許多選
        self.tableView?.allowsMultipleSelectionDuringEditing = true

        //綁定對長按的響應
        let longPress =  UILongPressGestureRecognizer(target:self,
                                                      action:#selector(ViewController.tableviewCellLongPressed(_:)))
        longPress.delegate = self
        longPress.minimumPressDuration = 1.0
        self.tableView!.addGestureRecognizer(longPress)
    }

    //單元格長按事件響應
    func tableviewCellLongPressed(gestureRecognizer:UILongPressGestureRecognizer)
    {
        if (gestureRecognizer.state == UIGestureRecognizerState.Ended)
        {
            print("UIGestureRecognizerStateEnded");
            //在正常狀態和編輯狀態之間切換
            if(self.tableView!.editing == false) {
                self.tableView!.setEditing(true, animated:true)
            }
            else {
                self.tableView!.setEditing(false, animated:true)
            }
        }
    }

    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1;
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.items.count
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath)
        -> UITableViewCell
    {
        let identify:String = "SwiftCell"
        let cell = tableView.dequeueReusableCellWithIdentifier(identify,
                                                              forIndexPath: indexPath) as UITableViewCell
        cell.textLabel?.text = self.items[indexPath.row]
        return cell
    }

    //刪除按鈕點擊
    @IBAction func btnClick(sender: AnyObject) {
        //獲取選中項索引
        var selectedIndexs = [Int]()
        if let selectedItems = tableView!.indexPathsForSelectedRows {
            for indexPath in selectedItems {
                selectedIndexs.append(indexPath.row)
            }
        }

        //刪除選中的數據
        items.removeAtIndexes(selectedIndexs)
        //重新加載數據
        self.tableView?.reloadData()
        //退出編輯狀態
        self.tableView!.setEditing(false, animated:true)
    }
}

extension Array {
    //Array方法擴展,支持根據索引數組刪除
    mutating func removeAtIndexes(ixs: [Int]) {
        for i in ixs.sort(>) {
            self.removeAtIndex(i)
        }
    }
}

批次刪除時索引一定要由大到小處理,這也是 sort(>) 的原因;若由小到大,前面的刪除會讓後面的索引全部位移,結果就會刪錯行。

該選哪一種?

只是要收集使用者勾選結果、介面維持列表樣子,用做法二最省力;需要「進入編輯模式才批量操作」的 deletion 體驗,就用做法三;若設計稿要求自繪勾選樣式或跨 section 記錄狀態,做法一反而最好控制。

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