#iOS單選和多選

開始做單選和多選的時(shí)候在網(wǎng)上找了好久,發(fā)現(xiàn)要么是單選,要么是多選,共存的教程幾乎沒有。因此自己研究了下,寫了個(gè)簡(jiǎn)單的demo用于分享

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

1.單選刪除的實(shí)現(xiàn)

2.多選刪除的實(shí)現(xiàn)。

3.單選和多選的共存。

4.多選按鈕的定制。

5.左滑添加按鈕

實(shí)現(xiàn)

語法:Object-C
1.簡(jiǎn)單的創(chuàng)建應(yīng)用等這里不再贅述,將直接在ViewController中進(jìn)行操作

2.寫了四個(gè)屬性

@property (nonatomic, strong) NSMutableArray *dataArray;//數(shù)據(jù)源
@property (nonatomic, strong) UITableView *listTableView;
@property (nonatomic, strong) NSMutableArray *selectedArray;//存儲(chǔ)被選擇的數(shù)據(jù)
@property (nonatomic, strong) NSMutableArray *deleteIndexPaths;//存儲(chǔ)indexpath

重寫tableView的get方法。

- (UITableView *)listTableView {
    if (!_listTableView) {
        _listTableView = [[UITableView alloc]initWithFrame:self.view.frame style:UITableViewStylePlain];
        _listTableView.delegate = self;
        _listTableView.dataSource = self;
//必須要加上,實(shí)現(xiàn)多選的必要方法
        _listTableView.allowsMultipleSelectionDuringEditing = YES;
    }
    return _listTableView;
}

viewDidLoad的實(shí)現(xiàn)

//初始化數(shù)組
_selectedArray = [NSMutableArray array];
_deleteIndexPaths = [NSMutableArray array];
_dataArray = [NSMutableArray array];
   //導(dǎo)航欄按鈕用系統(tǒng)定制,當(dāng)然如果你自定義導(dǎo)航欄,按鈕需要自己定制
   self.navigationItem.rightBarButtonItem = self.editButtonItem;
   
   //初始化數(shù)據(jù)源
   for (int i = 0; i < 10; i++) {
       [self.dataArray addObject:[NSString stringWithFormat:@"row %d",i]];
   }
   //創(chuàng)建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];
}


//點(diǎn)擊刪除的實(shí)現(xiàn)方法
- (void)deleteButtonClick:(UIButton *)button
{
   [_dataArray removeObjectsInArray:_selectedArray];
   
   [_listTableView deleteRowsAtIndexPaths:_deleteIndexPaths withRowAnimation:UITableViewRowAnimationFade];
   [_deleteIndexPaths removeAllObjects];
   [_selectedArray removeAllObjects];
   NSLog(@"buttonClick:");

}

//更新編輯和done之間的切換及tableview的編輯狀態(tài)。
- (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的實(shí)現(xiàn)

#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的實(shí)現(xiàn)

單選刪除的實(shí)現(xiàn) 當(dāng)然如果下面左滑打算添加按鈕,這里可不實(shí)現(xiàn),在下面的方法中實(shí)現(xiàn)

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

多選的選擇實(shí)現(xiàn),刪除方法在上面

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if ([tableView isEditing]) {
        //說明 在這里對(duì)左邊選擇的圓圈按鈕進(jìn)行定制,系統(tǒng)默認(rèn)的為藍(lán)色,這里有時(shí)候可能層級(jí)會(huì)發(fā)生過變化,因此做了判斷。
        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];
        }
    }

}


左滑按鈕的添加和方法的實(shí)現(xiàn)


//左滑添加按鈕
-(NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewRowAction *likeAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"喜歡" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        // 實(shí)現(xiàn)相關(guān)的邏輯代碼
        // ...
        // 在最后希望cell可以自動(dòng)回到默認(rèn)狀態(tài),所以需要退出編輯模式
        NSLog(@"點(diǎn)擊了喜歡按鈕");
        tableView.editing = NO;
    }];
    
    UITableViewRowAction *deleteAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"刪除" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        NSLog(@"點(diǎn)擊了刪除按鈕");
        
        [_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.初始化數(shù)據(jù)源和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.刪除方法及編輯設(shè)置

    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("點(diǎn)擊了喜歡按鈕");
            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上,如果你感覺有幫助就加個(gè)star吧

演示圖

image
image

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 發(fā)現(xiàn) 關(guān)注 消息 iOS 第三方庫、插件、知名博客總結(jié) 作者大灰狼的小綿羊哥哥關(guān)注 2017.06.26 09:4...
    肇東周閱讀 15,424評(píng)論 4 61
  • 什么是Nginx? Nginx是一個(gè)高性能的HTTP和反向代理服務(wù)器,也是一個(gè)IMAP/POP3/SMTP代理服務(wù)...
    BLUeyes閱讀 547評(píng)論 0 0
  • 從院子里到街道上 金黃的閃電擊碎了生活的銅墻鐵壁 在只有老人和孩子的城市里 青春是荒誕的 一日三餐 我終日低著頭 ...
    邊緣_閱讀 290評(píng)論 1 3
  • 首先請(qǐng)大家欣賞成品。 接下來就是作畫的步驟。 1.首先選好水彩紙,用圓規(guī)畫個(gè)圓,注意的是圓規(guī)的釘子不要扎破作畫的紙...
    小小何夕飯飯閱讀 888評(píng)論 12 34
  • 【青蓮堂日話】160119 每日一話,是為日話 狀態(tài)低迷的切爾西從5月份的英超冠軍滑落到如今的保級(jí)邊緣球隊(duì),至今沒...
    effelee閱讀 611評(píng)論 0 0

友情鏈接更多精彩內(nèi)容