Swift tableView的儲存格多選功能的實現(擷取多選值、多選刪除)

來源:互聯網
上載者:User

有時候在我們應用中需要用到表格(tableView)的多選功能。其實 tableView 已內建了多種多選功能,不用藉助第三方組件也可以實現。下面分別進行介紹。

方法1,自訂一個數組儲存選中項的索引(非編輯狀態)

(1)我們先定義一個數組,表格在非編輯狀態時,點擊某個儲存格便將其索引添加到這個數組中。同時將儲存格尾部打勾表示選中狀態。再次點擊原來選中的儲存格,則取消選中狀態,並將索引從數組中移除。

(2)點擊導覽列上的“確定”按鈕,即可擷取到所有選中項的索引以及對應的值,並列印出來。

 


import UIKit
 
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    
    var items:[String] = ["條目1","條目2","條目3","條目4","條目5"]
    
    //儲存選中儲存格的索引
    var selectedIndexs = [Int]()
    
    var tableView:UITableView?
    
    override func loadView() {
        super.loadView()
    }
    
    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
    }
    
    //建立各單元顯示內容(建立參數indexPath指定的單元)
    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])
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

方法2,將allowsMultipleSelection設定為true(非編輯狀態)

前面的範例,表格實際上還是單選的。只不過我們定義了一個數值來儲存選中的儲存格索引,從而實現多選的功能。

下面還是實現同樣的功能,只不過這次將表格設定成允許多選(allowsMultipleSelection 為 true),這樣我們也就不用再另外定義數組來儲存選中項索引了。

 


import UIKit
 
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    
    var items:[String] = ["條目1","條目2","條目3","條目4","條目5"]
    
    var tableView:UITableView?
    
    override func loadView() {
        super.loadView()
    }
    
    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
    }
    
    //建立各單元顯示內容(建立參數indexPath指定的單元)
    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])
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

方法3,allowsMultipleSelectionDuringEditing設定為true(編輯狀態)
這個範例同上面那個有點類似,只不過是表格進入編輯狀態下才可以多選。
(1)下面範例表格預設情況下無法進行多選。
(2)長按表格進入編輯狀態,這時儲存格前面會出現選擇框。點擊即可進行儲存格的選擇與取消。
(3)點擊導覽列上的“刪除”按鈕,即可將選中的儲存格都刪除。

 


 

import UIKit
 
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource,
                    UIGestureRecognizerDelegate {
    
    var items:[String] = ["條目1","條目2","條目3","條目4","條目5"]
    
    var tableView:UITableView?
    
    override func loadView() {
        super.loadView()
    }
    
    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
    }
    
    //建立各單元顯示內容(建立參數indexPath指定的單元)
    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)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}
 
extension Array {
    //Array方法擴充,支援根據索引數組刪除
    mutating func removeAtIndexes(ixs: [Int]) {
        for i in ixs.sort(>) {
            self.removeAtIndex(i)
        }
    }
}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.