iOS swift UITableView的編輯,全選发绢,刪除操作

iOS中UITableView經(jīng)常會(huì)出現(xiàn)需要對(duì)cell進(jìn)行編輯硬耍,全選,刪除等操作边酒,在navigationItem的BarButtonItems上加載按鈕经柴,效果圖如下


untitle.gif

我這里是,刪除了現(xiàn)有的墩朦,如果還有數(shù)據(jù)坯认,會(huì)繼續(xù)加載,看之前寫(xiě)的上拉刷新跟下拉加載更多氓涣,上代碼牛哺,代碼里把上拉刷新,下拉加載代碼去掉了春哨,如有需要完整可以留言或私聊我

//
//  MESsagneVC.swift
//  ios
//
//  Created by 李鑫豪 on 2018/8/16.
//  Copyright ? 2018年 李鑫豪. All rights reserved.
//

import UIKit
import SwiftyJSON
import ESPullToRefresh
class MESsagneVC: UIViewController,UITableViewDelegate,UITableViewDataSource{
 //懶加載
    lazy var myTableView: UITableView = {
        let vc = UITableView()
        vc.isEditing = false//默認(rèn)設(shè)為不可編輯荆隘。點(diǎn)擊編輯才可編輯
        return vc
    }()
   var pageNumber = 2  //第一次加載為1,因?yàn)榇蜷_(kāi)界面的時(shí)候已經(jīng)加載第一頁(yè)了赴背,默認(rèn)下拉的時(shí)候加載第二頁(yè)
    var messageCount = 0    //初始數(shù)
    var messageOriginalCount = 0      //加載時(shí)的原始數(shù)量
//編輯按鈕
    lazy var rightBtn: UIButton = {
        let btn = UIButton()
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 16)
        btn.setTitle("編輯", for: .normal)//默認(rèn)為編輯
        btn.setTitle("完成", for: .selected)//點(diǎn)擊之后為完成
        btn.setTitleColor(UIColor.blue, for: .normal)
        btn.setTitleColor(UIColor.blue, for: .selected)
        btn.addTarget(self, action: #selector(rightBtnAction), for: .touchUpInside)
        return btn
    }()
//刪除按鈕
    lazy var deleteBtn: UIButton = {
        let btn = UIButton()
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 16)
        btn.setTitle("刪除", for: .normal)//默認(rèn)為刪除
        btn.setTitleColor(UIColor.blue, for: .normal)
        btn.addTarget(self, action: #selector(deleteBtnAction), for: .touchUpInside)
        return btn
    }()
//全選按鈕
    lazy var allBtn: UIButton = {
        let btn = UIButton()
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 16)
        btn.setTitle("全選", for: .normal)//默認(rèn)為全選
        btn.setTitle("取消", for: .selected)//點(diǎn)擊全選之后為取消
        btn.setTitleColor(UIColor.blue, for: .normal)
        btn.setTitleColor(UIColor.blue, for: .selected)
        btn.isHidden = true  //默認(rèn)不顯示全選
        btn.addTarget(self, action: #selector(allBtnAction), for: .touchUpInside)
        return btn
    }()
    var value : [JSON] = []//result數(shù)組
    var messageData :[MESsageModel] = []//數(shù)據(jù)源
    var selectArray :[MESsageModel] = []//選擇數(shù)據(jù)數(shù)組
    func getCooksData(isDeletALL:Bool,pageNumber:Int,pageSize:Int,completed:@escaping ()->Void)  {
        //  isDeletALL:是否刪除數(shù)據(jù)源重新加載數(shù)據(jù)
        //pageNumber:加載頁(yè)數(shù)
         //pageSize:每頁(yè)的數(shù)據(jù)數(shù)椰拒。pageNumber晶渠,pageSize都是服務(wù)器的參數(shù)
        api.message_page_app(classification: -1, pageNumber: pageNumber, pageSize: pageSize){
            [weak self] result in
            guard let `self` = self else {return}
            if isDeletALL{
                self.messageData = []
            }
            self.messageOriginalCount = self.messageCount
            self.value = result["rows"].arrayValue
            for item in self.value
            {
                //處理返回的服務(wù)器返回的result 這里因人而異
                let message = MESsageModel()
                message.title = item["title"].stringValue
                message.content = item["content"].stringValue
                message.createTime = item["createTime"].stringValue
                message.id = item["id"].intValue
                self.messageData.append(message)
            }
            self.messageCount = self.messageData.count
            self.myTableView.reloadData()
            completed()
        }
    }
    override func viewDidLoad() {
        super.viewDidLoad()
       //設(shè)置數(shù)據(jù)源,代理
        myTableView.dataSource = self
        myTableView.delegate = self
        //布局
        self.view.addSubview(myTableView)
        myTableView.snp.makeConstraints{
            make in
            make.top.equalToSuperview().offset(tableNaiHeight)
            make.bottom.equalToSuperview()
            make.left.equalToSuperview()
            make.right.equalToSuperview()
        }
        //設(shè)置navigationItem.rightBarButtonItems為編輯燃观,全選褒脯,默認(rèn)不加載刪除按鈕
        navigationItem.rightBarButtonItems = [UIBarButtonItem(customView: rightBtn),UIBarButtonItem(customView: allBtn)]
        //下面為獲取數(shù)據(jù)
        getCooksData(isDeletALL: true,pageNumber: 1,pageSize: 20,completed: {})
        navigationItem.title = "消息"
    }
    override func viewWillAppear(_ animated: Bool) {
        self.navigationController?.setNavigationBarHidden(false, animated: true)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    // MARK: - Target
    @objc private func rightBtnAction(){
        self.selectArray.removeAll()//點(diǎn)擊編輯之后要把選擇數(shù)據(jù)源為空,因?yàn)槟J(rèn)點(diǎn)擊全選時(shí)所有都是未選中的
        rightBtn.isSelected = !rightBtn.isSelected//設(shè)置選擇狀態(tài)
        allBtn.isSelected = !rightBtn.isSelected//設(shè)置全選按鈕選擇狀態(tài)為選中即是全選
        allBtn.isHidden = !rightBtn.isSelected//設(shè)置是否隱藏全選按鈕
        if rightBtn.isSelected {
//如果點(diǎn)擊編輯按鈕缆毁,則rightBtn.isSelected為true番川,加載刪除button
            self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: deleteBtn)
            myTableView.setEditing(true, animated: true)//設(shè)置myTableView為可編輯狀態(tài)
        } else {
          //else則為再次點(diǎn)擊,恢復(fù)成原狀脊框,把刪除button移除颁督,設(shè)置myTableView為不可編輯狀態(tài),如果不移除刪除button浇雹,刪除button會(huì)占用navigationController的默認(rèn)返回按鈕
            self.navigationItem.leftBarButtonItems = []
            myTableView.setEditing(false, animated: true)
        }
    }
    @objc private func deleteBtnAction(){
        //如果selectArray.count沉御,則選擇數(shù)量大于0,有選cell
        if selectArray.count > 0 {
            var ids: [Int] = []
            //拿到selectArray里面的model昭灵,取id吠裆,為ids數(shù)組
            for model in selectArray{
                ids.append(model.id!)
            }
            //把ids發(fā)送給服務(wù)器,刪除服務(wù)器數(shù)據(jù)
            api.message_del_app(id: ids){
                [weak self] status,mess in
                if status == 0{
                    myHUD.showSuccess(mess: mess)
                    self?.myTableView.isEditing = false
                    self?.selectArray = []
                    self?.getCooksData(isDeletALL: true,pageNumber: 1,pageSize: 20,completed: {})
                }
                else {
                    myHUD.showFailed(mess: mess)
                }
            }
            //點(diǎn)擊刪除后烂完,把編輯button設(shè)置為未選中试疙,全選button設(shè)置不可見(jiàn),設(shè)置 myTableView為不可編輯
            rightBtn.isSelected = false
            allBtn.isHidden = true
            self.navigationItem.leftBarButtonItems = []
            myTableView.setEditing(false, animated: true)
        }
        else {
            self.view.makeToast("請(qǐng)選擇要?jiǎng)h除的消息")
        }
        
        
    }
    @objc private func allBtnAction(){
        //設(shè)置全選為選中抠蚣,則title為取消
        allBtn.isSelected = !allBtn.isSelected
        rightBtn.isSelected = allBtn.isSelected
        if allBtn.isSelected {
            let count = self.messageData.count
            var indexArray :[IndexPath] = []
          //獲取所有cell的IndexPath
            if count > 0 {
                for i in 0...count - 1{
                    let index = IndexPath(row: i, section: 0)
                    indexArray.append(index)
                }
            }
            selectArray.removeAll()//移除現(xiàn)有選擇數(shù)組的數(shù)據(jù)
            selectArray = messageData//將數(shù)據(jù)源的所有數(shù)據(jù)賦值給選擇數(shù)據(jù)
            for index in indexArray{
              選中所有的數(shù)組
                myTableView.selectRow(at: index, animated: false, scrollPosition: UITableViewScrollPosition.none)
            }
        } else {
          //取消操作祝旷,把selectArray為空
            selectArray.removeAll()
            myTableView.setEditing(false, animated: true)//設(shè)置為不可編輯
            allBtn.isHidden = true//隱藏
            self.navigationItem.leftBarButtonItems = []//移除刪除按鈕
        }
    }
    
    // MARK: - Table view data source
    
     func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }
    
     func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return messageData.count
    }
    
     func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 60
    }
    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true//返回可編輯
    }
    func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle {
//這里非常關(guān)鍵!
        return UITableViewCellEditingStyle(rawValue: UITableViewCellEditingStyle.delete.rawValue | UITableViewCellEditingStyle.insert.rawValue)!
    }
     func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let reuesname = "cell"
        
        var cell = tableView.dequeueReusableCell(withIdentifier: reuesname) as?MESsagneCell
        if cell == nil {
            cell = MESsagneCell(style: UITableViewCellStyle.default, reuseIdentifier: reuesname)
        }
        cell?.title.text = messageData[indexPath.row].title!
        cell?.content.text = messageData[indexPath.row].content!
        cell?.createTime.text = messageData[indexPath.row].createTime!

        
        return cell!
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if tableView.isEditing {
            let select = self.messageData[indexPath.row]
            if (!self.selectArray.contains(select)) {
                self.selectArray.append(select)
                
            }
        }
    }
    func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
        let select = self.messageData[indexPath.row]
        if (self.selectArray.contains(select)) {
            let index = selectArray.index(of: select)
            selectArray.remove(at: index!)
        }
    }
}

謝謝柱徙,如果寫(xiě)的不好還希望指出缓屠,如果恰巧能滿(mǎn)足你的需求奇昙,請(qǐng)點(diǎn)個(gè)喜歡

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末护侮,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子储耐,更是在濱河造成了極大的恐慌羊初,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,509評(píng)論 6 504
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件什湘,死亡現(xiàn)場(chǎng)離奇詭異长赞,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)闽撤,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,806評(píng)論 3 394
  • 文/潘曉璐 我一進(jìn)店門(mén)得哆,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人哟旗,你說(shuō)我怎么就攤上這事贩据《安伲” “怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 163,875評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵饱亮,是天一觀的道長(zhǎng)矾芙。 經(jīng)常有香客問(wèn)我,道長(zhǎng)近上,這世上最難降的妖魔是什么剔宪? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,441評(píng)論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮壹无,結(jié)果婚禮上葱绒,老公的妹妹穿的比我還像新娘。我一直安慰自己斗锭,他們只是感情好哈街,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,488評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著拒迅,像睡著了一般骚秦。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上璧微,一...
    開(kāi)封第一講書(shū)人閱讀 51,365評(píng)論 1 302
  • 那天作箍,我揣著相機(jī)與錄音,去河邊找鬼前硫。 笑死胞得,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的屹电。 我是一名探鬼主播阶剑,決...
    沈念sama閱讀 40,190評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼危号!你這毒婦竟也來(lái)了牧愁?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 39,062評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤外莲,失蹤者是張志新(化名)和其女友劉穎猪半,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體偷线,經(jīng)...
    沈念sama閱讀 45,500評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡磨确,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,706評(píng)論 3 335
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了声邦。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片乏奥。...
    茶點(diǎn)故事閱讀 39,834評(píng)論 1 347
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖亥曹,靈堂內(nèi)的尸體忽然破棺而出邓了,到底是詐尸還是另有隱情盏檐,我是刑警寧澤,帶...
    沈念sama閱讀 35,559評(píng)論 5 345
  • 正文 年R本政府宣布驶悟,位于F島的核電站胡野,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏痕鳍。R本人自食惡果不足惜硫豆,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,167評(píng)論 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望笼呆。 院中可真熱鬧熊响,春花似錦、人聲如沸诗赌。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,779評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)铭若。三九已至洪碳,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間叼屠,已是汗流浹背瞳腌。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 32,912評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留镜雨,地道東北人嫂侍。 一個(gè)月前我還...
    沈念sama閱讀 47,958評(píng)論 2 370
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像荚坞,于是被迫代替她去往敵國(guó)和親挑宠。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,779評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容

  • 1颓影、通過(guò)CocoaPods安裝項(xiàng)目名稱(chēng)項(xiàng)目信息 AFNetworking網(wǎng)絡(luò)請(qǐng)求組件 FMDB本地?cái)?shù)據(jù)庫(kù)組件 SD...
    陽(yáng)明先生_X自主閱讀 15,980評(píng)論 3 119
  • 昨天跟孩子一起背誦了《與時(shí)間賽跑》各淀,課文通過(guò)外祖母的去世憂傷不已,后來(lái)在爸爸一席話的啟示下瞭空,和時(shí)間賽跑揪阿,最后體會(huì)到...
    鄭彩云_aa1b閱讀 136評(píng)論 0 2
  • 1.“堅(jiān)持”兩個(gè)字一直給我的感覺(jué)是在苦苦的支撐疗我,如“再堅(jiān)持一下就好了”咆畏,是的這對(duì)于完成一件眼前的事情可以給以支撐,...
    放平自我閱讀 256評(píng)論 0 0
  • ——坐,食茶 成了大家對(duì)潮汕人的既有印象麦牺,除了牛肉丸就是功夫茶钮蛛。 潮汕人不可一日無(wú)茶鞭缭,所以茶...
    木_拾音閱讀 1,280評(píng)論 2 3
  • 意識(shí)恢復(fù)的時(shí)候,自己正走在一條路上魏颓。也有可能不是路岭辣,因?yàn)樗闹芤黄岷冢裁炊伎床坏降楸ィ瓦B自己的身體也看不清沦童,而...
    老三家的老三閱讀 333評(píng)論 0 3