Swift實(shí)現(xiàn)表格視圖單元格多選
本文實(shí)例為大家分享了Swift實(shí)現(xiàn)表格視圖單元格多選的具體代碼,供大家參考,具體內(nèi)容如下
效果

前言
這段時(shí)間比較忙,沒(méi)太多的時(shí)間寫(xiě)博客,前段時(shí)間寫(xiě)了一些關(guān)于表格視圖單選的文章,想著,一并把多選也做了,今天剛好有時(shí)間,去做這樣一件事情。多選在我們的應(yīng)用程序中也是常見(jiàn)的,比如消息的刪除,群發(fā)聯(lián)系人的選擇,音樂(lè)的添加等等可能都會(huì)涉及到多選的需求,本文,我將模擬多選刪除消息來(lái)講講多選的實(shí)現(xiàn)。
原理
多選刪除其實(shí)很簡(jiǎn)單,并不復(fù)雜,我的思路就是創(chuàng)建一個(gè)數(shù)組,當(dāng)用戶選中某個(gè)單元格的時(shí)候,取到單元格上對(duì)應(yīng)的數(shù)據(jù),把它存入數(shù)組中,如果用戶取消選中,直接將數(shù)據(jù)從數(shù)組中移除。當(dāng)用戶點(diǎn)擊刪除時(shí),直接遍歷數(shù)組,將表格視圖數(shù)據(jù)源數(shù)組里面的與存選擇數(shù)據(jù)的數(shù)組中的數(shù)據(jù)相對(duì)應(yīng)一一刪除,再刷新表格視圖即可。
實(shí)現(xiàn)
界面搭建很簡(jiǎn)單,創(chuàng)建一個(gè)表格視圖,添加導(dǎo)航欄,并在上面添加一個(gè)刪除按鈕,這里我就不細(xì)說(shuō)了。
在ViewController 中,我們先聲明幾個(gè)屬性,其中 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!) ??
}此時(shí),系統(tǒng)會(huì)報(bào)警告,提示你沒(méi)有遵守協(xié)議,因?yàn)槲覀冊(cè)诔跏蓟砀褚晥D的時(shí)候?yàn)槠湓O(shè)置了代理和數(shù)據(jù)源,遵守協(xié)議,并實(shí)現(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)中我只做了一個(gè)操作,就是根據(jù)單元格選中狀態(tài)來(lá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)顯示出來(lái)了,下面我們將開(kāi)始處理多選刪除的邏輯,當(dāng)我們點(diǎn)擊單元格的時(shí)候發(fā)現(xiàn),只能單選???我要怎么去多選呢?此時(shí)我們需要在配置表格視圖的地方設(shè)置 allowsMultipleSelection 屬性,將其值設(shè)為 YES。
tableView.allowsMultipleSelection = true
接下來(lái),實(shí)現(xiàn)代理方法 didSelectRowAtIndexPath: 與 didDeselectRowAtIndexPath:,這里我們將修改單元格選中與未選中狀態(tài)下的顏色,只需根據(jù)參數(shù)indexPath獲取到單元格,修改 backgroundColor 屬性,并且,我們還需要獲取單元格上的數(shù)據(jù),去操作selectedDatas數(shù)組,具體實(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),再?gòu)臄?shù)組中刪除元素的,可能有的人會(huì)問(wèn),不能像OC一樣調(diào)用removeObject:方法根據(jù)數(shù)據(jù)直接刪除元素嗎?并不能,因?yàn)镾wift 提供的刪除數(shù)組元素的方法中,大都是根據(jù)下標(biāo)來(lái)刪除數(shù)組元素的。
接下來(lái),我們需要執(zhí)行刪除邏輯了,在刪除按鈕觸發(fā)的方法中,我們要做的第一件事情就是異常處理,如果 selectedDatas 數(shù)組為空或者該數(shù)組并未初始化,我們無(wú)需再做刪除處理,彈框提示即可。
// Exception handling
if (self.selectedDatas == nil) || (self.selectedDatas?.isEmpty == true) {
? ? let alertController = UIAlertController(title: "溫馨提示", message: "請(qǐng)選擇您要?jiǎng)h除的數(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()
為了提高用戶體驗(yàn),我們可以彈框提示用戶刪除成功,直接在后面加上以下代碼。
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 ,而是通過(guò)一個(gè)延遲調(diào)用,來(lái)讓彈出框自動(dòng)消失,這樣就避免了用戶再次點(diǎn)擊彈出框按鈕來(lái)隱藏,提升用戶體驗(yàn)。
OK,到了這一步,基本已經(jīng)實(shí)現(xiàn)了,但是有一個(gè)小瑕疵,那就是當(dāng)我刪除了單元格的時(shí)候,界面上某些單元格會(huì)呈現(xiàn)選中狀態(tài)的背景顏色,解決辦法非常簡(jiǎn)單,我們只需要在配置單元格的協(xié)議方法中加上這一句話即可。
cell?.backgroundColor = UIColor.whiteColor()
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
LeetCode?題解?Swift?有效的完全平方數(shù)
這篇文章主要為大家介紹了LeetCode?題解?Swift?有效的完全平方數(shù)方案示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-09-09
Swift語(yǔ)言中字符串相關(guān)的基本概念解析
這篇文章主要介紹了Swift語(yǔ)言中字符串相關(guān)的基本概念解析,是Swift入門(mén)學(xué)習(xí)中的基礎(chǔ)知識(shí),需要的朋友可以參考下2015-11-11
SwiftUI學(xué)習(xí)之state和Binding的區(qū)別淺析
這篇文章主要給大家介紹了關(guān)于SwiftUI學(xué)習(xí)之state和Binding區(qū)別的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(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)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者使用Swift具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-08-08
Swift如何調(diào)用Objective-C的可變參數(shù)函數(shù)詳解
這篇文章主要給大家介紹了關(guān)于Swift如何調(diào)用Objective-C的可變參數(shù)函數(shù)的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用swift具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧。2018-03-03
詳解Swift編程中的for循環(huán)的編寫(xiě)方法
這篇文章主要介紹了Swift編程中的for循環(huán)的編寫(xiě)方法,包括相關(guān)的for...in循環(huán),需要的朋友可以參考下2015-11-11

