标签:ios单选复选实现 tableview单选复选 tableviewcontroller实
iOS中如何实现多选?
基本思路是给cell绑定的数据设置一个标志位,
用来标识该cell是否被选中,
如果被选中则修改该标志位为YES,
并且把选中的行加入到可变数组中
如果选中时该标志位为YES则说明已经选中
那么此时需要需要把该标志位修改为NO
并且从选中数组中移除
实现过程,参考上一篇单选实现文章:http://blog.csdn.net/yangbingbinga/article/details/47057285:
(1)创建相关的TableViewController
使用系统的Cell
有Person类映射Cell的数据
还包括是否选中的标识位
(2)关键代码
//
// TableViewController2.m
// app39-表视图8-单选复选
//
// Created by MRBean on 15/7/24.
// Copyright (c) 2015年 yangbin. All rights reserved.
#import "TableViewController2.h" #import "Person.h" @interface TableViewController2 () @property(strong,nonatomic)NSMutableArray *marr; @property(strong,nonatomic)NSMutableArray *selectRows; @end
@implementation TableViewController2
- (void)viewDidLoad {
[super viewDidLoad];
_marr = [[NSMutableArray alloc]init];
_selectRows = [NSMutableArray new];
for (int i=0; i<20; i++)//产生大量假数据
{
Person *p = [[Person alloc]init];
p.title = [NSString stringWithFormat:@"%iTitle",i];
p.detail = [NSString stringWithFormat:@"%iDetail",i];
p.ifSelected = NO;
[_marr addObject:p];
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return _marr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ACELL" forIndexPath:indexPath];
Person *p = _marr[indexPath.row];
cell.textLabel.text = p.title;
cell.detailTextLabel.text = p.detail;
if(p.ifSelected)
cell.accessoryType = UITableViewCellAccessoryCheckmark;
else cell.accessoryType = UITableViewCellAccessoryNone;
return cell;
}
//选中后改变数据
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
Person *p = _marr[indexPath.row];
if (p.ifSelected)//如果该行已经选择,则第二次是取消改行被选中
{
p.ifSelected = NO;//取消选中
[_selectRows removeObject:@(indexPath.row)];//重数组中移除
}
else
{
p.ifSelected = YES;//选中
[_selectRows addObject:@(indexPath.row)];
}
[tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];//刷新该行
//添加到数组中,此操作可能会导致有重复的数据
}
- (IBAction)tapSubmit:(UIBarButtonItem *)sender
{
NSMutableString *mstr = [[NSMutableString alloc]initWithString:@"你选中的行数有:"];
[_selectRows enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
[mstr appendFormat:@"%@,",obj];
}];
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:mstr message:nil delegate:nil cancelButtonTitle:@"我知道了" otherButtonTitles:nil, nil];
[alert show];
}
@end
单选的实现:http://blog.csdn.net/yangbingbinga/article/details/47057285
版权声明:本文为博主原创文章,未经博主允许不得转载。
iOS开发-UITableViewController复选/多选实现2
标签:ios单选复选实现 tableview单选复选 tableviewcontroller实
原文地址:http://blog.csdn.net/yangbingbinga/article/details/47057747