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è)喜歡