iOS swift UITableView的编辑,全选,删除操作

iOS中UITableView经常会出现需要对cell进行编辑,全选,删除等操作,在navigationItem的BarButtonItems上加载按钮,效果图如下


untitle.gif

我这里是,删除了现有的,如果还有数据,会继续加载,看之前写的上拉刷新跟下拉加载更多,上代码,代码里把上拉刷新,下拉加载代码去掉了,如有需要完整可以留言或私聊我

//
//  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//默认设为不可编辑。点击编辑才可编辑
        return vc
    }()
   var pageNumber = 2  //第一次加载为1,因为打开界面的时候已经加载第一页了,默认下拉的时候加载第二页
    var messageCount = 0    //初始数
    var messageOriginalCount = 0      //加载时的原始数量
//编辑按钮
    lazy var rightBtn: UIButton = {
        let btn = UIButton()
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 16)
        btn.setTitle("编辑", for: .normal)//默认为编辑
        btn.setTitle("完成", for: .selected)//点击之后为完成
        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)//默认为删除
        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)//默认为全选
        btn.setTitle("取消", for: .selected)//点击全选之后为取消
        btn.setTitleColor(UIColor.blue, for: .normal)
        btn.setTitleColor(UIColor.blue, for: .selected)
        btn.isHidden = true  //默认不显示全选
        btn.addTarget(self, action: #selector(allBtnAction), for: .touchUpInside)
        return btn
    }()
    var value : [JSON] = []//result数组
    var messageData :[MESsageModel] = []//数据源
    var selectArray :[MESsageModel] = []//选择数据数组
    func getCooksData(isDeletALL:Bool,pageNumber:Int,pageSize:Int,completed:@escaping ()->Void)  {
        //  isDeletALL:是否删除数据源重新加载数据
        //pageNumber:加载页数
         //pageSize:每页的数据数。pageNumber,pageSize都是服务器的参数
        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
            {
                //处理返回的服务器返回的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()
       //设置数据源,代理
        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()
        }
        //设置navigationItem.rightBarButtonItems为编辑,全选,默认不加载删除按钮
        navigationItem.rightBarButtonItems = [UIBarButtonItem(customView: rightBtn),UIBarButtonItem(customView: allBtn)]
        //下面为获取数据
        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()//点击编辑之后要把选择数据源为空,因为默认点击全选时所有都是未选中的
        rightBtn.isSelected = !rightBtn.isSelected//设置选择状态
        allBtn.isSelected = !rightBtn.isSelected//设置全选按钮选择状态为选中即是全选
        allBtn.isHidden = !rightBtn.isSelected//设置是否隐藏全选按钮
        if rightBtn.isSelected {
//如果点击编辑按钮,则rightBtn.isSelected为true,加载删除button
            self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: deleteBtn)
            myTableView.setEditing(true, animated: true)//设置myTableView为可编辑状态
        } else {
          //else则为再次点击,恢复成原状,把删除button移除,设置myTableView为不可编辑状态,如果不移除删除button,删除button会占用navigationController的默认返回按钮
            self.navigationItem.leftBarButtonItems = []
            myTableView.setEditing(false, animated: true)
        }
    }
    @objc private func deleteBtnAction(){
        //如果selectArray.count,则选择数量大于0,有选cell
        if selectArray.count > 0 {
            var ids: [Int] = []
            //拿到selectArray里面的model,取id,为ids数组
            for model in selectArray{
                ids.append(model.id!)
            }
            //把ids发送给服务器,删除服务器数据
            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)
                }
            }
            //点击删除后,把编辑button设置为未选中,全选button设置不可见,设置 myTableView为不可编辑
            rightBtn.isSelected = false
            allBtn.isHidden = true
            self.navigationItem.leftBarButtonItems = []
            myTableView.setEditing(false, animated: true)
        }
        else {
            self.view.makeToast("请选择要删除的消息")
        }
        
        
    }
    @objc private func allBtnAction(){
        //设置全选为选中,则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()//移除现有选择数组的数据
            selectArray = messageData//将数据源的所有数据赋值给选择数据
            for index in indexArray{
              选中所有的数组
                myTableView.selectRow(at: index, animated: false, scrollPosition: UITableViewScrollPosition.none)
            }
        } else {
          //取消操作,把selectArray为空
            selectArray.removeAll()
            myTableView.setEditing(false, animated: true)//设置为不可编辑
            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 {
//这里非常关键!
        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!)
        }
    }
}

谢谢,如果写的不好还希望指出,如果恰巧能满足你的需求,请点个喜欢

你可能感兴趣的:(iOS swift UITableView的编辑,全选,删除操作)