UItableView的刪除(多選刪除)以及UITableViewCell方法重寫

通常在對tableView的數據有編輯操做的時候,會用到tableView的編輯狀態,如收藏等須要操做的界面。編輯狀態下能夠對tableView進行增刪改等的一系列操做,這裏主要針對多選刪除,對選刪除的時候會涉及到cell的左側對選按鈕(圖片)的設置,須要重寫UITableViewCell的setEdting,setHighlighted,setSelected等方法,其中:setEdting只須要設置未選中狀態圖片;setHighlighted只須要設置高亮狀態選中狀態圖片,非高亮狀態不用設置;setSelected須要設置選中和未選中狀態的圖片api

import UIKit

class CKBaseCell: UITableViewCell {

    override func awakeFromNib() {
        super.awakeFromNib()
    }
    
    override func setEditing(_ editing: Bool, animated: Bool) {
        super.setEditing(editing, animated: true)
        
        //編輯狀態下只控制tableView編輯狀態.none狀態的圖片
        if editing{
            for control in self.subviews{
                if control.isMember(of: NSClassFromString("UITableViewCellEditControl")!) {
                    for view in control.subviews{
                        if view.isKind(of: UIImageView.classForCoder()){
                            let image = view as! UIImageView
                            image.image = #imageLiteral(resourceName: "ic_collection_unchecked")
                        }
                    }
                }
            }
        }
    }
    
    override func setHighlighted(_ highlighted: Bool, animated: Bool) {
        super.setHighlighted(highlighted, animated: animated)
        if highlighted == true {
            contentView.backgroundColor = CKGlobalConst.ColorF4
        } else {
            contentView.backgroundColor = .white
        }
        
        //控制高亮狀態的圖片
        if isEditing {
            for control in self.subviews{
                if control.isMember(of: NSClassFromString("UITableViewCellEditControl")!) {
                    for view in control.subviews{
                        if view.isKind(of: UIImageView.classForCoder()){
                            let image = view as! UIImageView
                            //只設置高亮狀態就能夠,若是設置了else爲未選中圖片的話,當cell滑出界面或者刷新界面的話,即使cell狀態設置爲了已選中狀態圖片也會由於是非高亮狀態而顯示未選中圖片
                            if highlighted {
                                image.image = #imageLiteral(resourceName: "ic_topic_checked")
                            }
                        }
                    }
                }
            }
        }
    }
    
    override func setSelected(_ selected: Bool, animated: Bool) {
//        super.setHighlighted(selected, animated: animated)
        super.setSelected(selected, animated: animated)
        if selected == true {
            contentView.backgroundColor = CKGlobalConst.ColorF4
        } else {
            contentView.backgroundColor = .white
        }
        
        //控制選中狀態圖片(實例:收藏,選中後刷新或cell滑出界面以後,再出現的時候判斷選中數組中是否包含該行cell,包含的話就將該行狀態設置爲選中狀態,只要是選中狀態就會走這個方法)
        if isEditing{
            for control in self.subviews{
                if control.isMember(of: NSClassFromString("UITableViewCellEditControl")!) {
                    for view in control.subviews{
                        if view.isKind(of: UIImageView.classForCoder()){
                            let image = view as! UIImageView
                            if selected{
                                image.image = #imageLiteral(resourceName: "ic_topic_checked")
                            }else{
                                image.image = #imageLiteral(resourceName: "ic_collection_unchecked")
                            }
                        }
                    }
                }
            }
        }
    }
}

在tableView中,若是cell滑出了界面或者界面進行刷新了的時候,須要在cellForRow的方法中判斷當前cell是否包含於「要刪除的數組」,包含於「要刪除的數組」的cell設置其setSelected/isSelected爲選中狀態(True)數組

import UIKit

class CKCollectionController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    
    var tableView: UITableView?
    var editButton = UIButton()
    var articleModelArray: [CKArticleModel] = []
    //要刪除的文章ID
    var deleteIdArray: [String] = []
    //要刪除的cell行數
    var deleteIndexArray: [String] = []
    let promptView = CKPromptView()
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.setNavigationBarHidden(false, animated: true)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.white
        setNaviBar()
        setupUI()
        loadData()
    }
    
    func setNaviBar() {
        editButton.setTitle("    Edit   ", for: .normal)
        editButton.setTitleColor(UIColor.colorWithHex(hex: 0x35b3fc), for: .normal)
        editButton.titleLabel?.font = UIFont.systemFont(ofSize: 16)
        editButton.addTarget(self, action: #selector(editClick), for: .touchUpInside)
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: editButton)
        navigationItem.title = "Collection"
    }
    
    func loadData() {
        //第一次加載,顯示loding
        if self.articleModelArray.count == 0 {
            //添加loading全局缺省圖
            promptView.addDefaultView(self.view, #imageLiteral(resourceName: "loading"), CKMultilingual.loading)
        }
        
        //無網的時候,直接不請求
        if !CKUtil.isConnectedToNetwork() {
            promptView.removeDefaultView()
            if self.articleModelArray.count == 0 {
                //第一次加載或者總體數據爲空,添加全局缺省圖
                promptView.addDefaultView(self.view, #imageLiteral(resourceName: "no network"), CKMultilingual.Network_connection_is_abnormal, CKMultilingual.Click_on_the_screen_to_try_again, #selector(self.loadData))
            }
            return
        }
        
        let collectApi = CKCollectAPI()
        collectApi.callbackSuccess = { api in
            //清除loading
            self.promptView.removeDefaultView()
            
            var modelArray: [CKArticleModel] = []
            modelArray = (api as! CKCollectAPI).articleModelArray
            self.articleModelArray = modelArray
            if self.articleModelArray.count == 0 {
                //總體沒有數據,添加全局缺省圖
                self.promptView.addDefaultView(self.view, #imageLiteral(resourceName: "no content"), CKMultilingual.No_content_yet)
                self.editButton.setTitleColor(UIColor.gray, for: .normal)
                self.editButton.isUserInteractionEnabled = false
            }else{
                self.editButton.setTitleColor(UIColor.blue, for: .normal)
                self.editButton.isUserInteractionEnabled = true
            }
            self.tableView?.reloadData()
        }
        
        collectApi.callbackFailure = { error in
            print("\(error)")
            self.promptView.removeDefaultView()
            if self.articleModelArray.count == 0 {
                //總體沒有數據,添加全局缺省圖
                self.promptView.addDefaultView(self.view, #imageLiteral(resourceName: "no content"), CKMultilingual.No_content_yet)
            }
        }
        
        collectApi.execute()
    }
    
    func setupUI() {
        let tableView = UITableView(frame: .zero, style: .plain)
        tableView.delegate = self
        tableView.dataSource = self
        //編輯狀態可多選
        tableView.allowsMultipleSelectionDuringEditing = true
        tableView.estimatedRowHeight = 180
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.showsVerticalScrollIndicator = false
        tableView.backgroundColor = CKGlobalConst.ColorF4
        view.addSubview(tableView)
        self.tableView = tableView
        
        // 註冊單圖cell
        tableView.register(UINib.init(nibName: "CKNormalCell", bundle: nil), forCellReuseIdentifier: CKGlobalConst.normalCellID)
        // 註冊多圖圖cell
        tableView.register(UINib.init(nibName: "CKMultiImageCell", bundle: nil), forCellReuseIdentifier: CKGlobalConst.multiImageCellID)
        // 註冊無圖cell
        tableView.register(UINib.init(nibName: "CKNoImageCell", bundle: nil), forCellReuseIdentifier: CKGlobalConst.noImageCellID)
        // 註冊大圖cell
        tableView.register(UINib.init(nibName: "CKLargeImageCell", bundle: nil), forCellReuseIdentifier: CKGlobalConst.largeImageCellID)
        // 視頻cell
        tableView.register(UINib.init(nibName: "CKVideoCell", bundle: nil), forCellReuseIdentifier: "CKVideoCellID")
        
        tableView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
            make.center.equalToSuperview()
        }
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return articleModelArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        var reuseID:String = CKGlobalConst.normalCellID
        if (articleModelArray[indexPath.row].images()?.count) ?? 0 >= 3{
            reuseID = CKGlobalConst.multiImageCellID
        } else if (articleModelArray[indexPath.row].images()?.count)  ?? 0 == 0 {
            reuseID = CKGlobalConst.noImageCellID
        } else if articleModelArray[indexPath.row].ctype == 1 {
            reuseID = CKGlobalConst.largeImageCellID
        }
        
        let cell: CKBaseCell = tableView.dequeueReusableCell(withIdentifier: reuseID, for: indexPath) as! CKBaseCell
        cell.model = articleModelArray[indexPath.row]
        
        //先判斷文章是否已閱讀
        if UserDefaults.standard.bool(forKey: "isRead\(String(describing: cell.model?.articleid))") == true {
            cell.titleLabel.textColor = UIColor.colorWithHex(hex: 0x989898)
        } else {
            cell.titleLabel.textColor = CKGlobalConst.Color2
        }
        
        if deleteIndexArray.count != 0 {
            for index in deleteIndexArray{
                if (index as NSString).integerValue == indexPath.row{
                    tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none)
//                    cell.setSelected(true, animated: false)
                    cell.isSelected = true
                }
            }
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if tableView.isEditing {
            let cell: CKBaseCell = tableView.cellForRow(at: indexPath) as! CKBaseCell
            cell.isSelected = true
            //添加要刪除cell的信息
            deleteIndexArray.append(String(describing: indexPath.row))
            //添加要刪除的文章ID
            deleteIdArray.append(String(describing: articleModelArray[indexPath.row].id ?? 0))
            editButton.setTitle("Delete", for: .normal)
        }else{
            print(articleModelArray[indexPath.row])
            
            tableView.deselectRow(at: indexPath, animated: true)
            let detailController = CKDetailViewController()
            let cell: CKBaseCell = tableView.cellForRow(at: indexPath) as! CKBaseCell

            //存儲已閱讀狀態
            UserDefaults.standard.set(true, forKey: "isRead\(String(describing: cell.model?.articleid))")
            cell.titleLabel.textColor = UIColor.colorWithHex(hex: 0x989898)
            detailController.articleModel = cell.model

            let navigationController: CKNavigationController = UIApplication.shared.keyWindow?.rootViewController as! CKNavigationController
            navigationController.pushViewController(detailController, animated: true)

            //MARK: - 數據埋點: 文章id
            CKUtil.setGatherWith("21", "1", "1", nil)
        }
    }
    
    func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
        if tableView.isEditing{
            let cell: CKBaseCell = tableView.cellForRow(at: indexPath) as! CKBaseCell
            cell.isSelected = false
            //刪除要取消刪除cell的信息
            deleteIndexArray.remove(at: deleteIndexArray.index(of: String(describing: indexPath.row))!)
            //刪除要取消刪除的文章ID
            deleteIdArray.remove(at: deleteIdArray.index(of: String(describing: articleModelArray[indexPath.row].id ?? 0))!)
            if deleteIndexArray.count == 0 {
                editButton.setTitle("Cancel", for: .normal)
            }
        }
    }
    
    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }
    
    //開始左滑刪除操做時候的操做
    func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle {
        editButton.isEnabled = false
        return .delete
    }
    
    //結束左滑刪除操做的時候的操做
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == UITableViewCellEditingStyle.delete {
            
            let delCollectApi = CKDeleteCollect()
            delCollectApi.articleids = String(describing: articleModelArray[indexPath.row].id ?? 0)
            delCollectApi.callbackSuccess = {api in
                self.articleModelArray.remove(at: indexPath.row)
                tableView.deleteRows(at: [indexPath], with: .left)//平滑效果
            }
            delCollectApi.callbackFailure = {api in
                
            }
            delCollectApi.execute()
        }
        tableView.reloadData()
    }
    
    //左滑刪除後的操做
    func tableView(_ tableView: UITableView, didEndEditingRowAt indexPath: IndexPath?) {
        editButton.isEnabled = true
    }
    
    func editClick() {
        editButton.isSelected = !editButton.isSelected
        if editButton.isSelected {
            if deleteIndexArray.count != 0{
                deleteIndexArray.removeAll()
            }
            if deleteIdArray.count != 0{
                deleteIdArray.removeAll()
            }
            editButton.setTitle("Cancel", for: .normal)
            tableView?.setEditing(true, animated: true)
        }else{
            editButton.setTitle("  Edit  ", for: .normal)
            tableView?.setEditing(false, animated: true)
            
            let delCollectApi = CKDeleteCollect()
            delCollectApi.articleids = deleteIdArray.joined(separator: ",")
            delCollectApi.callbackSuccess = {api in}
            delCollectApi.callbackFailure = {api in}
            delCollectApi.execute()
            
            var delIdArray:[CKArticleModel] = []
            for index in self.deleteIndexArray{
                delIdArray.append(self.articleModelArray[(index as NSString).integerValue])
            }
            //獲取要刪除的文章ID
            for model in delIdArray{
                self.articleModelArray.remove(at: self.articleModelArray.index(of: model)!)
            }
            self.deleteIndexArray.removeAll()
            self.deleteIdArray.removeAll()
            tableView?.reloadData()
        }
    }
    
}
相關文章
相關標籤/搜索