#iOS单选和多选

作者: Terry_S | 来源:发表于2016-06-23 15:34 被阅读3501次

开始做单选和多选的时候在网上找了好久,发现要么是单选,要么是多选,共存的教程几乎没有。因此自己研究了下,写了个简单的demo用于分享

注意:看完后你可以得到什么?

1.单选删除的实现

2.多选删除的实现。

3.单选和多选的共存。

4.多选按钮的定制。

5.左滑添加按钮

实现

语法:Object-C
1.简单的创建应用等这里不再赘述,将直接在ViewController中进行操作

2.写了四个属性

@property (nonatomic, strong) NSMutableArray *dataArray;//数据源
@property (nonatomic, strong) UITableView *listTableView;
@property (nonatomic, strong) NSMutableArray *selectedArray;//存储被选择的数据
@property (nonatomic, strong) NSMutableArray *deleteIndexPaths;//存储indexpath

重写tableView的get方法。

- (UITableView *)listTableView {
    if (!_listTableView) {
        _listTableView = [[UITableView alloc]initWithFrame:self.view.frame style:UITableViewStylePlain];
        _listTableView.delegate = self;
        _listTableView.dataSource = self;
//必须要加上,实现多选的必要方法
        _listTableView.allowsMultipleSelectionDuringEditing = YES;
    }
    return _listTableView;
}

viewDidLoad的实现

//初始化数组
_selectedArray = [NSMutableArray array];
_deleteIndexPaths = [NSMutableArray array];
_dataArray = [NSMutableArray array];
   //导航栏按钮用系统定制,当然如果你自定义导航栏,按钮需要自己定制
   self.navigationItem.rightBarButtonItem = self.editButtonItem;
   
   //初始化数据源
   for (int i = 0; i < 10; i++) {
       [self.dataArray addObject:[NSString stringWithFormat:@"row %d",i]];
   }
   //创建tableview和button
   [self createUI];

-(void)createUI {
   [self.view addSubview:self.listTableView];
   
   UIButton *deleteButton = [UIButton buttonWithType:UIButtonTypeCustom];
   [deleteButton setTitle:@"删除" forState:UIControlStateNormal];
   [deleteButton setBackgroundColor:[UIColor orangeColor]];
   deleteButton.frame = CGRectMake(0, CGRectGetMaxY(self.view.frame) - 40, self.view.frame.size.width, 40);
   [self.view addSubview:deleteButton];
   [deleteButton addTarget:self action:@selector(deleteButtonClick:) forControlEvents:UIControlEventTouchUpInside];
}


//点击删除的实现方法
- (void)deleteButtonClick:(UIButton *)button
{
   [_dataArray removeObjectsInArray:_selectedArray];
   
   [_listTableView deleteRowsAtIndexPaths:_deleteIndexPaths withRowAnimation:UITableViewRowAnimationFade];
   [_deleteIndexPaths removeAllObjects];
   [_selectedArray removeAllObjects];
   NSLog(@"buttonClick:");

}

//更新编辑和done之间的切换及tableview的编辑状态。
- (void)setEditing:(BOOL)editing animated:(BOOL)animated {
   if ([_listTableView isEditing]) {
       self.editButtonItem.title = @"Edit";
       [_listTableView setEditing:NO animated:YES];
       
   } else {
       self.editButtonItem.title = @"Done";
       [_listTableView setEditing:YES animated:YES];
   }
}

tableviewDataSource的实现

#pragma mark -- UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return _dataArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[ UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
    cell.textLabel.text = self.dataArray[indexPath.row];
    return cell;
}

tableview Delegate的实现

单选删除的实现 当然如果下面左滑打算添加按钮,这里可不实现,在下面的方法中实现

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [_dataArray removeObjectAtIndex:indexPath.row];
    
    [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}

多选的选择实现,删除方法在上面

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if ([tableView isEditing]) {
        //说明 在这里对左边选择的圆圈按钮进行定制,系统默认的为蓝色,这里有时候可能层级会发生过变化,因此做了判断。
        if (cell.subviews.count > 3) {
            if (cell.subviews[3].subviews[0]) {
                ((UIImageView *)(cell.subviews[3].subviews[0])).image = [UIImage imageNamed:@"xz"];
            }
        } else {
            if (cell.subviews[2].subviews[0]) {
                ((UIImageView *)(cell.subviews[2].subviews[0])).image = [UIImage imageNamed:@"xz"];
            }
        }
        [_selectedArray addObject:_dataArray [indexPath.row]];
        [_deleteIndexPaths addObject:indexPath];
    }
}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];

    if ([tableView isEditing]) {
        if (cell.subviews.count > 3) {
            if (cell.subviews[3].subviews[0]) {
                ((UIImageView *)(cell.subviews[3].subviews[0])).image = [UIImage imageNamed:@""];
            } else {
                if (cell.subviews[2].subviews[0]) {
                    ((UIImageView *)(cell.subviews[2].subviews[0])).image = [UIImage imageNamed:@""];
                }
            
            }
        }

        if ([_selectedArray containsObject:_dataArray[indexPath.row]]) {
            [_selectedArray removeObject:_dataArray[indexPath.row]];
            [_deleteIndexPaths removeObject:indexPath];
        }
    }

}


左滑按钮的添加和方法的实现


//左滑添加按钮
-(NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewRowAction *likeAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"喜欢" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        // 实现相关的逻辑代码
        // ...
        // 在最后希望cell可以自动回到默认状态,所以需要退出编辑模式
        NSLog(@"点击了喜欢按钮");
        tableView.editing = NO;
    }];
    
    UITableViewRowAction *deleteAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"删除" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        NSLog(@"点击了删除按钮");
        
        [_dataArray removeObjectAtIndex:indexPath.row];
        
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }];
    
    return @[deleteAction, likeAction];

}

语法:Swift

    var listTableView: UITableView!
    var dataArray:NSMutableArray!
    let cellIdentifier = "cellIdentifier";
    var delteteIndexPaths:NSMutableArray!
    var selectArray:NSMutableArray!

2.初始化数据源和UI

    func initUIAndData(){
        
        self.navigationItem.rightBarButtonItem = self.editButtonItem()
        dataArray = NSMutableArray.init(capacity: 0)
        selectArray = NSMutableArray.init(capacity: 0)
        delteteIndexPaths = NSMutableArray.init(capacity: 0)
        
        listTableView = UITableView.init(frame: self.view.frame, style: .Plain);
        listTableView?.delegate = self;
        listTableView?.dataSource = self;
        listTableView.allowsMultipleSelectionDuringEditing = true;
        self.view.addSubview(listTableView!)
        
        for i in 0...10 {
            dataArray.addObject("row:\(i)")
        }
        
        let deleteButton = UIButton.init(type: .Custom)
        deleteButton.frame = CGRectMake(0, CGRectGetMaxY(self.view.frame) - 40, self.view.frame.width, 40)
        deleteButton .setTitle("删除", forState: .Normal);
        deleteButton.backgroundColor = UIColor.orangeColor();
        deleteButton .addTarget(self, action: #selector(ViewController.deleteButtonClick(_:)), forControlEvents: UIControlEvents.TouchUpInside)
        self.view.addSubview(deleteButton)
        
    }

3.删除方法及编辑设置

    func deleteButtonClick(sender:UIButton) {
        dataArray .removeObjectsInArray(selectArray as [AnyObject])
        listTableView .deleteRowsAtIndexPaths(delteteIndexPaths as AnyObject as! [NSIndexPath], withRowAnimation: .Fade)
        delteteIndexPaths .removeAllObjects()
        selectArray.removeAllObjects()
    }

 override func setEditing(editing: Bool, animated: Bool) {
        super.setEditing(editing, animated: animated);
        
        if listTableView.editing {
            self.editButtonItem().title = "Edit";
            listTableView.setEditing(false, animated: true)
        } else {
            self.editButtonItem().title = "Done";
            listTableView .setEditing(true, animated: animated)
        }
    }

4.UITableviewDatasourse的代理方法

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataArray!.count;
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let cell = cellForTableView(tableView);
        cell.textLabel?.text = dataArray[indexPath.row] as? String;
        return cell;
    }

4.delegate代理方法


extension ViewController:UITableViewDelegate {
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        let cell = tableView.cellForRowAtIndexPath(indexPath);
        if tableView.editing {
            if cell?.subviews.count > 3 {
                if let _ = cell?.subviews[3].subviews[0]{
                    let imageView:UIImageView = cell!.subviews[3].subviews[0] as! UIImageView
                    imageView.image = UIImage(named:"xz");
                    
                }
            }else {
                if let _ = cell?.subviews[2].subviews[0]{
                    let imageView:UIImageView = cell!.subviews[2].subviews[0] as! UIImageView
                    imageView.image = UIImage(named:"xz");
                    
                }
            }
        }
       
        selectArray.addObject(dataArray![indexPath.row])
        delteteIndexPaths.addObject(indexPath)
        
    }
    
    func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
        
        if selectArray.containsObject(dataArray[indexPath.row]) {
            selectArray.removeObject(dataArray[indexPath.row])
            delteteIndexPaths.removeObject(indexPath)
        }
    }

    func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? {
    
        let likeAction = UITableViewRowAction(style: .Normal, title: "喜欢", handler:{ action, indexPath in
            
            print("点击了喜欢按钮");
            tableView.editing = false

        
        })
        
        let deleteAction = UITableViewRowAction(style: .Default, title: "删除", handler: { action, indexPath in
                self.dataArray.removeObjectAtIndex(indexPath.row)
                tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
        
        
        })
        return [likeAction,deleteAction]
        
        
    }

就是这样,代码已传到git上,如果你感觉有帮助就加个star吧

演示图

imageimage

相关文章

  • #iOS单选和多选

    开始做单选和多选的时候在网上找了好久,发现要么是单选,要么是多选,共存的教程几乎没有。因此自己研究了下,写了个简单...

  • iOS UITableView 单选和多选

    hello,iOS小伙伴们,最近都在搞单选和多选,我为大家总结了一下,虽然网上都能早到,但是都是零零闪闪的;几行代...

  • iOS UICollectionView单选和多选

    hello,iOS小伙伴们,上次研究了tableView,这次是UICollectionView,其实和table...

  • iOS tableView实现单选和多选

    今天在项目中遇到了tableView的单选需求,现在总结一下,用一个简单的demo实现了简单的单选和多选两个功能....

  • iOS TableView的单选和多选

    前言 在平时的开发tableview可以说是用到的最多的控件了,而且tableview的单选和多选也并不少见,今天...

  • iOS tableView实现单选和多选

    今天在项目中遇到了tableView的单选需求,现在总结一下,用一个简单的demo实现了简单的单选和多选两个功能....

  • 更换单选与多选样式

    HTML: JQ: CSS: 单选与多选img: 单选: 多选:

  • 『心善渊』Selenium3.0基础 — 18.单选按钮和多选按

    1、页面中的单选按钮和多选按钮 页面中的单选按钮和多选按钮样式如下图: 页面代码片段: 说明: 单选按钮,默认选框...

  • 今日份学习进度

    做了份增值税章的单选和多选题 单选18道对17道,还不错 多选16题对6道,惨不忍睹 好在单选多选都是2分,不然太...

  • 2017-12-27

    IOS轻松搞定button单选,多选,反选标签 (1)创建KKTipView继承于UIView .h文件内容 //...

网友评论

  • 贱精先玍丶:我创建一个项目跟楼主你的demo一模一样的代码怎么点删除报错了....而且感觉报错的好像是数组越界的问题【reason: 'Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (20) must be equal to the number of rows contained in that section before the update (20), plus or minus the number of rows inserted or deleted from that section (0 inserted, 3 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).'】
    Terry_S:嗯,最近没上简书,有时间我我更新下代码。
  • 知德:非编辑状态,左滑出现删除按钮,然后执行方法使tableView进入编辑状态
    然后有删除按钮的cell:右边删除按钮不消失,左侧多选框不出现
    怎么解决???
  • 8290a89231af:楼主 我自定义选择勾颜色, cell划上去再划回来 就变成系统的蓝色了, 你解决了吗?
    贱精先玍丶:@Terry_S 怎么替换里面的图片呢?
    8290a89231af:@Terry_S 恩 我也是 换成图片才可以的....
    Terry_S:@cheng080010 我开始尝试过,那个选框是不能自定义颜色的吧,我也是替换了他里面的图片

  • Zeayal:学习
  • macfai:不错学习了
    macfai:@Terry_S :smile::clap:
    Terry_S:共同进步😊
  • 喵猫刘::clap:
    Terry_S:谢谢支持😊
  • 海绵是海鲜:写的非常好 很适合用来写购物车 但是 存在一个小问题就是 cell选中放入复用池之后 cell头部的编辑选择按钮就重新被渲染成蓝色了 已关注
    YoRuo_:@这样你说 放入一个可变数组,然后看数组有没有。有的话就selected=YES没有就不操作。
    Terry_S:恩,没有发现,有时间我再看看😊

本文标题:#iOS单选和多选

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