#iOS单选和多选

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

演示图

image
image

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,233评论 4 360
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,013评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,030评论 0 241
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,827评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,221评论 3 286
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,542评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,814评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,513评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,225评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,497评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,998评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,342评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,986评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,055评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,812评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,560评论 2 271
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,461评论 2 266

推荐阅读更多精彩内容

  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 11,609评论 4 59
  • 什么是Nginx? Nginx是一个高性能的HTTP和反向代理服务器,也是一个IMAP/POP3/SMTP代理服务...
    BLUeyes阅读 475评论 0 0
  • 从院子里到街道上 金黄的闪电击碎了生活的铜墙铁壁 在只有老人和孩子的城市里 青春是荒诞的 一日三餐 我终日低着头 ...
    边缘_阅读 205评论 1 3
  • 首先请大家欣赏成品。 接下来就是作画的步骤。 1.首先选好水彩纸,用圆规画个圆,注意的是圆规的钉子不要扎破作画的纸...
    小小何夕饭饭阅读 795评论 12 34
  • 【青莲堂日话】160119 每日一话,是为日话 状态低迷的切尔西从5月份的英超冠军滑落到如今的保级边缘球队,至今没...
    effelee阅读 409评论 0 0