iOS TableView的單選和多選

前言

在平時的開發(fā)tableview可以說是用到的最多的控件了,而且tableview的單選和多選也并不少見种冬,今天就來討論下tableview的單選和多選镣丑。

單選

單選的邏輯其實就是記錄選中的indexpath,然后當(dāng)用戶選擇cell的時候把上次選中的cell取消碌廓,選中本次選擇的cell

#import "SingleSelectViewController.h"

@interface SingleSelectViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) UITableView     *tableView;
@property (nonatomic, strong) NSMutableArray  *dataArray;
@property (nonatomic, strong) NSIndexPath     *selectedIndexPath;

@end

@implementation SingleSelectViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"single select";
    
    [self setupViews];
}

- (void)setupViews{
    
    for (NSInteger i = 0; i < 10; i ++) {
        NSString *str = [NSString stringWithFormat:@">>>>>%lu",i];
        [self.dataArray addObject:str];
    }
    
    
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    self.tableView.dataSource = self;
    self.tableView.delegate   = self;
    self.tableView.tableFooterView = [UIView new];
    self.tableView.cellLayoutMarginsFollowReadableWidth = NO;
    [self.view addSubview:self.tableView];
    
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *identifier = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    if (self.selectedIndexPath && self.selectedIndexPath == indexPath) {
        cell.textLabel.textColor = [UIColor blueColor];
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    }else{
        cell.textLabel.textColor = [UIColor blackColor];
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    
    cell.textLabel.text = self.dataArray[indexPath.row];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UITableViewCell *cell;
    
    /*NSIndexPath *indexPath = [NSIndexPath indexPathForRow:sender.tag inSection:0];*/ /*如果是點擊cell上子控件可用此方法找到對應(yīng)path*/
    
    if (self.selectedIndexPath) {
        cell = [self.tableView cellForRowAtIndexPath:self.selectedIndexPath];
        cell.textLabel.textColor = [UIColor blackColor];
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    
    cell = [self.tableView cellForRowAtIndexPath:indexPath];
    cell.textLabel.textColor = [UIColor blueColor];
    cell.accessoryType = UITableViewCellAccessoryCheckmark;
    
    self.selectedIndexPath = indexPath;
    [self.tableView reloadData];
}

- (NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end

多選

多選的邏輯也不復(fù)雜传轰,主要是再編輯狀態(tài)下記錄用戶選擇了哪些cell,在editingStyleForRowAtIndexPath里返回UITableViewCellEditingStyleDelete | UITableViewCellEditingStyleInsert就可以設(shè)置多選谷婆,多選的時候只要操作相應(yīng)的數(shù)據(jù)就可以了

#import "MoreSelectViewController.h"

@interface MoreSelectViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) UITableView    *tableView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) NSMutableArray *selectArray;

@end

@implementation MoreSelectViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.title = @"more select";
    
    [self setupViews];
    
}

- (void)setupViews{
    
    for (NSInteger i = 0; i < 10; i ++) {
        NSString *str = [NSString stringWithFormat:@">>>>>%lu",i];
        [self.dataArray addObject:str];
    }
    
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithTitle:@"編輯" style:UIBarButtonItemStyleDone target:self action:@selector(editAction:)];
    self.navigationItem.rightBarButtonItem = item;
    
    
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    self.tableView.dataSource = self;
    self.tableView.delegate   = self;
    self.tableView.tableFooterView = [UIView new];
    self.tableView.cellLayoutMarginsFollowReadableWidth = NO;
    [self.view addSubview:self.tableView];
    
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *identifier = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    
    cell.textLabel.text = self.dataArray[indexPath.row];
    
    return cell;
}

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

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSString *str = self.dataArray[indexPath.row];
    [self.selectArray addObject:str];
}
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *str = self.dataArray[indexPath.row];
    [self.selectArray removeObject:str];
}

- (void)editAction:(UIBarButtonItem *)item{
    if ([item.title isEqualToString:@"編輯"]) {
        if (self.dataArray.count == 0) {
            return;
        }
        item.title = @"取消";
        [self.tableView setEditing:YES animated:YES];
    }else{
        item.title = @"編輯";
        [self.tableView setEditing:NO animated:YES];
        
    }
    NSLog(@">>>>>>>>>>selectArrayCount : %lu",self.selectArray.count);
}

- (NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (NSMutableArray *)selectArray{
    if (!_selectArray) {
        _selectArray = [NSMutableArray array];
    }
    return _selectArray;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end

Demo在這里下載

總結(jié)

以上就是對TableView單選和多選的一些總結(jié)慨蛙,如果有寫的不好的地方,請多多指正纪挎。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末期贫,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子异袄,更是在濱河造成了極大的恐慌通砍,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,542評論 6 504
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異封孙,居然都是意外死亡迹冤,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,822評論 3 394
  • 文/潘曉璐 我一進(jìn)店門虎忌,熙熙樓的掌柜王于貴愁眉苦臉地迎上來泡徙,“玉大人,你說我怎么就攤上這事膜蠢】懊辏” “怎么了?”我有些...
    開封第一講書人閱讀 163,912評論 0 354
  • 文/不壞的土叔 我叫張陵挑围,是天一觀的道長礁竞。 經(jīng)常有香客問我,道長杉辙,這世上最難降的妖魔是什么模捂? 我笑而不...
    開封第一講書人閱讀 58,449評論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮蜘矢,結(jié)果婚禮上枫绅,老公的妹妹穿的比我還像新娘。我一直安慰自己硼端,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 67,500評論 6 392
  • 文/花漫 我一把揭開白布寓搬。 她就那樣靜靜地躺著珍昨,像睡著了一般。 火紅的嫁衣襯著肌膚如雪句喷。 梳的紋絲不亂的頭發(fā)上镣典,一...
    開封第一講書人閱讀 51,370評論 1 302
  • 那天,我揣著相機(jī)與錄音唾琼,去河邊找鬼兄春。 笑死,一個胖子當(dāng)著我的面吹牛锡溯,可吹牛的內(nèi)容都是我干的赶舆。 我是一名探鬼主播,決...
    沈念sama閱讀 40,193評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼祭饭,長吁一口氣:“原來是場噩夢啊……” “哼芜茵!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起倡蝙,我...
    開封第一講書人閱讀 39,074評論 0 276
  • 序言:老撾萬榮一對情侶失蹤九串,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體猪钮,經(jīng)...
    沈念sama閱讀 45,505評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡品山,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,722評論 3 335
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了烤低。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片肘交。...
    茶點故事閱讀 39,841評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖拂玻,靈堂內(nèi)的尸體忽然破棺而出酸些,到底是詐尸還是另有隱情,我是刑警寧澤檐蚜,帶...
    沈念sama閱讀 35,569評論 5 345
  • 正文 年R本政府宣布魄懂,位于F島的核電站,受9級特大地震影響闯第,放射性物質(zhì)發(fā)生泄漏市栗。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,168評論 3 328
  • 文/蒙蒙 一咳短、第九天 我趴在偏房一處隱蔽的房頂上張望填帽。 院中可真熱鬧,春花似錦咙好、人聲如沸篡腌。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,783評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽嘹悼。三九已至,卻和暖如春层宫,著一層夾襖步出監(jiān)牢的瞬間杨伙,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,918評論 1 269
  • 我被黑心中介騙來泰國打工萌腿, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留限匣,地道東北人。 一個月前我還...
    沈念sama閱讀 47,962評論 2 370
  • 正文 我出身青樓毁菱,卻偏偏與公主長得像米死,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子贮庞,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,781評論 2 354

推薦閱讀更多精彩內(nèi)容