技术文章分类(180)

技术随笔(11)

UITableview多选效果实现

github 下载demo:https://github.com/MartinLi841538513/MartinDemos (一切以demo为准)

 

首先你得会基本的tableview的集成,这里不多说了。在你会了基本的tableview的集成的基础上,你加上以下操作就可实现多选效果

先上效果图:

操作:

1,设置[self.tableview setEditing:YES animated:YES];

2,添加

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    return UITableViewCellEditingStyleDelete | UITableViewCellEditingStyleInsert;
}

大功告成,很简单吧。确实很简单,但实际项目中,你可能还需要获取数据,实时更新获取到的数据,所以我把所有代码上传到demo,大家自行下载,下面我也会给出详细代码

 

.h文件

#import <UIKit/UIKit.h>

@interface TableviewMutiSelectViewController : UIViewController<UITableViewDataSource,UITableViewDelegate>
@property(nonatomic,strong)NSArray *datas;
@property (weak, nonatomic) IBOutlet UITableView *tableview;
@property (weak, nonatomic) IBOutlet UILabel *label;
@end

 

.m文件

//
//  TableviewMutiSelectViewController.m
//  MartinDemos
//
//  Created by Gao Huang on 14-12-19.
//  Copyright (c) 2014年 Martin. All rights reserved.
//

#import "TableviewMutiSelectViewController.h"

@interface TableviewMutiSelectViewController ()

@end

@implementation TableviewMutiSelectViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.datas = [NSArray arrayWithObjects:@"1",@"2",@"3",@"4",@"5",@"6", nil];
    [self.tableview setEditing:YES animated:YES];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.datas.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];;
    cell.textLabel.text = self.datas[indexPath.row];
    return cell;
}
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    return UITableViewCellEditingStyleDelete | UITableViewCellEditingStyleInsert;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self updateDataWithTableview:tableView];
}
-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self updateDataWithTableview:tableView];
}
- (void)updateDataWithTableview:(UITableView *)tableView {
    NSArray *indexpaths = [tableView indexPathsForSelectedRows];
    NSMutableArray *selectedItems = [NSMutableArray new];
    for (NSIndexPath *indexpath in indexpaths) {
        UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexpath];
        [selectedItems addObject:cell.textLabel.text];
    }
    self.label.text = [selectedItems componentsJoinedByString:@";"];
}
@end

 

posted @ 2014-12-19 15:20  坤哥MartinLi  阅读(429)  评论(0编辑  收藏  举报