Swift實現(xiàn)表格視圖單元格多選
本文實例為大家分享了Swift實現(xiàn)表格視圖單元格多選的具體代碼,供大家參考,具體內(nèi)容如下
效果
前言
這段時間比較忙,沒太多的時間寫博客,前段時間寫了一些關(guān)于表格視圖單選的文章,想著,一并把多選也做了,今天剛好有時間,去做這樣一件事情。多選在我們的應(yīng)用程序中也是常見的,比如消息的刪除,群發(fā)聯(lián)系人的選擇,音樂的添加等等可能都會涉及到多選的需求,本文,我將模擬多選刪除消息來講講多選的實現(xiàn)。
原理
多選刪除其實很簡單,并不復(fù)雜,我的思路就是創(chuàng)建一個數(shù)組,當(dāng)用戶選中某個單元格的時候,取到單元格上對應(yīng)的數(shù)據(jù),把它存入數(shù)組中,如果用戶取消選中,直接將數(shù)據(jù)從數(shù)組中移除。當(dāng)用戶點(diǎn)擊刪除時,直接遍歷數(shù)組,將表格視圖數(shù)據(jù)源數(shù)組里面的與存選擇數(shù)據(jù)的數(shù)組中的數(shù)據(jù)相對應(yīng)一一刪除,再刷新表格視圖即可。
實現(xiàn)
界面搭建很簡單,創(chuàng)建一個表格視圖,添加導(dǎo)航欄,并在上面添加一個刪除按鈕,這里我就不細(xì)說了。
在ViewController
中,我們先聲明幾個屬性,其中 selectedDatas
主要用于記錄用戶選擇的數(shù)據(jù)。
var tableView: UITableView? var dataSource: [String]? var selectedDatas: [String]?
創(chuàng)建初始化方法,初始化屬性,別忘了還需要在 ViewDidLoad()
中調(diào)用方法初始化方法。
// MARK:Initialize methods func initializeDatasource() { ? ? self.selectedDatas = [] ? ? self.dataSource = [] ? ? for index in 1...10 { ? ? ? ? index < 10 ? self.dataSource?.append("消息0\(index)") : self.dataSource?.append("消息\(index)") ? ? } } func initializeUserInterface() { ? ? self.title = "消息" ? ? self.automaticallyAdjustsScrollViewInsets = false ? ? // Add delete navigation item ? ? self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "刪除", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("respondsToBarButtonItem:")) ? ? // table view ? ? self.tableView = { ? ? ? ? let tableView = UITableView(frame: CGRectMake(0, 64, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds)), style: UITableViewStyle.Plain) ? ? ? ? tableView.dataSource = self ? ? ? ? tableView.delegate = self ? ? ? ? tableView.tableFooterView = UIView() ? ? ? ? return tableView ? ? ? ? }() ? ? self.view.addSubview(self.tableView!) ?? }
此時,系統(tǒng)會報警告,提示你沒有遵守協(xié)議,因為我們在初始化表格視圖的時候為其設(shè)置了代理和數(shù)據(jù)源,遵守協(xié)議,并實現(xiàn)協(xié)議方法,配置數(shù)據(jù)源。
func numberOfSectionsInTableView(tableView: UITableView) -> Int { ? ? return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { ? ? return self.dataSource!.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { ? ? var cell: CustomTableViewCell? = tableView.dequeueReusableCellWithIdentifier("cellReuseIdentifier") as? CustomTableViewCell ? ? if cell == nil { ? ? ? ? cell = CustomTableViewCell(style: UITableViewCellStyle.Value1, reuseIdentifier: "cellReuseIdentifier") ? ? } ? ? cell!.selectionStyle = UITableViewCellSelectionStyle.None ? ? cell!.textLabel?.text = self.dataSource![indexPath.row] ? ? cell!.detailTextLabel?.text = "昨天 10-11" ? ? return cell! }
這里需要強(qiáng)調(diào)的是,表格視圖的單元格是自定義的,在自定義單元格(CustomTableViewCell)
中我只做了一個操作,就是根據(jù)單元格選中狀態(tài)來切換圖片的顯示。
override func setSelected(selected: Bool, animated: Bool) { ? ? super.setSelected(selected, animated: animated) ? ? if selected { ? ? ? ? self.imageView?.image = UIImage(named: "iconfont-selected") ? ? }else { ? ? ? ? self.imageView?.image = UIImage(named: "iconfont-select") ? ? } }
現(xiàn)在運(yùn)行程序,界面已經(jīng)顯示出來了,下面我們將開始處理多選刪除的邏輯,當(dāng)我們點(diǎn)擊單元格的時候發(fā)現(xiàn),只能單選???我要怎么去多選呢?此時我們需要在配置表格視圖的地方設(shè)置 allowsMultipleSelection
屬性,將其值設(shè)為 YES。
tableView.allowsMultipleSelection = true
接下來,實現(xiàn)代理方法 didSelectRowAtIndexPath:
與 didDeselectRowAtIndexPath:
,這里我們將修改單元格選中與未選中狀態(tài)下的顏色,只需根據(jù)參數(shù)indexPath
獲取到單元格,修改 backgroundColor
屬性,并且,我們還需要獲取單元格上的數(shù)據(jù),去操作selectedDatas
數(shù)組,具體實現(xiàn)如下。
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { ? ? let cell = tableView.cellForRowAtIndexPath(indexPath) ? ? cell?.backgroundColor = UIColor.cyanColor() ? ? self.selectedDatas?.append((cell!.textLabel?.text)!) } func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) { ? ? let cell = tableView.cellForRowAtIndexPath(indexPath) ? ? cell?.backgroundColor = UIColor.whiteColor() ? ? let index = self.selectedDatas?.indexOf((cell?.textLabel?.text)!) ? ? self.selectedDatas?.removeAtIndex(index!) }
在 didDeselectRowAtIndexPath:
方法中,我是根據(jù)表格視圖單元格上的數(shù)據(jù)獲取下標(biāo),再從數(shù)組中刪除元素的,可能有的人會問,不能像OC一樣調(diào)用removeObject:
方法根據(jù)數(shù)據(jù)直接刪除元素嗎?并不能,因為Swift 提供的刪除數(shù)組元素的方法中,大都是根據(jù)下標(biāo)來刪除數(shù)組元素的。
接下來,我們需要執(zhí)行刪除邏輯了,在刪除按鈕觸發(fā)的方法中,我們要做的第一件事情就是異常處理,如果 selectedDatas
數(shù)組為空或者該數(shù)組并未初始化,我們無需再做刪除處理,彈框提示即可。
// Exception handling if (self.selectedDatas == nil) || (self.selectedDatas?.isEmpty == true) { ? ? let alertController = UIAlertController(title: "溫馨提示", message: "請選擇您要刪除的數(shù)據(jù)!", preferredStyle: UIAlertControllerStyle.Alert) ? ? alertController.addAction(UIAlertAction(title: "確定", style: UIAlertActionStyle.Default, handler: nil)) ? ? self.presentViewController(alertController, animated: true, completion: nil) ? ? return }
異常處理之后,我們需要遍歷selectedDatas
數(shù)組,然后根據(jù)該數(shù)組中的數(shù)據(jù)獲取到該數(shù)據(jù)在數(shù)據(jù)源(dataSource
)里的下標(biāo),最后再根據(jù)該下標(biāo)將數(shù)據(jù)從數(shù)據(jù)源中刪除。
for data in self.selectedDatas! { ? ? // Get index with data ? ? let index = self.dataSource!.indexOf(data) ? ? // Delete data with index ? ? self.dataSource?.removeAtIndex(index!) }
現(xiàn)在我們只需要刷新表格視圖即可,當(dāng)然,selectedDatas
數(shù)組我們也需要清空,以備下一次用戶多選刪除使用。
self.tableView?.reloadData() self.selectedDatas?.removeAll()
為了提高用戶體驗,我們可以彈框提示用戶刪除成功,直接在后面加上以下代碼。
let alertController = UIAlertController(title: "溫馨提示", message: "數(shù)據(jù)刪除成功!", preferredStyle: UIAlertControllerStyle.Alert) self.presentViewController(alertController, animated: true, completion: nil) dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(1.0 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in ? ? self.presentedViewController?.dismissViewControllerAnimated(true, completion: nil) }
代碼中,我并未給彈出框添加action
,而是通過一個延遲調(diào)用,來讓彈出框自動消失,這樣就避免了用戶再次點(diǎn)擊彈出框按鈕來隱藏,提升用戶體驗。
OK,到了這一步,基本已經(jīng)實現(xiàn)了,但是有一個小瑕疵,那就是當(dāng)我刪除了單元格的時候,界面上某些單元格會呈現(xiàn)選中狀態(tài)的背景顏色,解決辦法非常簡單,我們只需要在配置單元格的協(xié)議方法中加上這一句話即可。
cell?.backgroundColor = UIColor.whiteColor()
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
LeetCode?題解?Swift?有效的完全平方數(shù)
這篇文章主要為大家介紹了LeetCode?題解?Swift?有效的完全平方數(shù)方案示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-09-09SwiftUI學(xué)習(xí)之state和Binding的區(qū)別淺析
這篇文章主要給大家介紹了關(guān)于SwiftUI學(xué)習(xí)之state和Binding區(qū)別的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-03-03深入探究Swift枚舉關(guān)聯(lián)值的內(nèi)存
這篇文章主要給大家介紹了關(guān)于Swift枚舉關(guān)聯(lián)值的內(nèi)存的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者使用Swift具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧2020-08-08Swift如何調(diào)用Objective-C的可變參數(shù)函數(shù)詳解
這篇文章主要給大家介紹了關(guān)于Swift如何調(diào)用Objective-C的可變參數(shù)函數(shù)的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家學(xué)習(xí)或者使用swift具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧。2018-03-03