美文网首页技巧iOS-swift
tableview系统自带的多选操作(全选,全不选,删除)

tableview系统自带的多选操作(全选,全不选,删除)

作者: func_老衲姓罗 | 来源:发表于2016-09-29 10:30 被阅读1811次

最近在写一个cell的多选操作,包括全选,全不选,多项删除,cell用的就是系统的cell

cell前面的勾选怎么出现?

先设置tableView.editing=true 然后实现下面代理方法,在下面打理方法中如果你只返回Insert 就会出现➕的图表在cell的左边,如果只返回Delete则出现➖的图表在左边,要想出现可勾选的图表,则如下面代码一样,返回两个

func  tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle {

return UITableViewCellEditingStyle.init(rawValue: UITableViewCellEditingStyle.Insert.rawValue | UITableViewCellEditingStyle.Delete.rawValue)!

全选怎么实现?

要想全选,当然首先要在编辑状态tableView.editing=true

//全选

}

func allSelected()

{

deleteArray.removeAll()

for i in 0...peoples.count-1{

let indexPath1=NSIndexPath(forRow: i,inSection: 0)

self.tableView.selectRowAtIndexPath(indexPath1, animated: true, scrollPosition: UITableViewScrollPosition.Top)

}

}

deleteArray是我声明的一个数组保存删除以后的元素,他的初始化时等于cell数据来源的那个数组

全不选怎么实现呢?

//全不选

func unAllSelected()

{

for i in 0...peoples.count-1{

let indexPath1=NSIndexPath(forRow: i,inSection: 0)

self.tableView.deselectRowAtIndexPath(indexPath1, animated: true)

}

}

删除的实现:声明一个数组,保存你点击的cell之外的元素,然后刷新列表。将剩下的元素展示出来

func delete()

{

peoples=deleteArray

tableView.reloadData()

}

当点击勾选的时候,将执行的是didSelectRowAtIndexPath这个代理方法

所以我们要在deleteArray中移除掉所在index的元素

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

//deleteArray .removeAtIndex(indexPath.row)

if deleteArray.contains(peoples[indexPath.row]) {

deleteArray.removeAtIndex(deleteArray.indexOf(peoples[indexPath.row])!)

}

print(deleteArray)

commitArray.insert(peoples[indexPath.row], atIndex: indexPath.row)

}

当我们再次点击取消勾选的时候,会执行didDeselectRowAtIndexPath这个方法

我们还要将移除的元素在加进去

func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {

deleteArray.insert(peoples[indexPath.row], atIndex: indexPath.row)

print(deleteArray)

}

相关文章

网友评论

  • 阿斯兰iOS:多选框:设置 allowsMultipleSelectionDuringEditing 和 edting = YES 就可以了

    删除:
    NSArray *indexPaths = [self.tableView indexPathsForSelectedRows];
    NSMutableArray *toRemove = [NSMutableArray arrayWithCapacity:indexPaths.count];

    for (NSIndexPath *indexPath in indexPaths) {
    [toRemove addObject:self.projects[indexPath.row]];
    }
    [self.projects removeObjectsInArray:toRemove];
    阿斯兰iOS: [self.tableView deleteRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationRight];

本文标题:tableview系统自带的多选操作(全选,全不选,删除)

本文链接:https://www.haomeiwen.com/subject/dlvkyttx.html