在项目中我们会经常遇到列表多选与全选的操作,其实现的方式有很多,以下就是我的一种实现方法。多选就是两种状态:选中和未选中,其思路是
1,首先是初始化一个可变数组和可变字典,遍历出每个cell的数值,给每个cell都符值为“0”(“0”代表未选中,“1”代表选中),加在字典中,在把字典加在数组中。
2,其次是,在cell中取出数组中 的值做判断,当值为“0”时,显示“未选中”状态。值为“1”时,显示“选中状态”。
3,在点击方法中,当点击的值是“0”,设置值的状态改变为“1”,并且刷新着一行cell 数据。反之
注意:但你取出cell的row 是需要做字符串的转换。
下面是Dome:
@interface ViewController ()<UITableViewDataSource, UITableViewDelegate>
{
NSMutableArray *arrDate;
NSMutableArray *arrStauts;
NSMutableDictionary *dic;
}
@property (nonatomic, strong) UITableView *tableView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
arrDate = [[NSMutableArray alloc] initWithObjects:@"苹果",@"梨子",@"香蕉",@"水果",@"蔬菜", nil];
_tableView = [[UITableView alloc] init];
_tableView.frame = CGRectMake(0, 20, self.view.frame.size.width, self.view.frame.size.height-20);
_tableView.dataSource = self;
_tableView.delegate = self;
[self.view addSubview:_tableView];
arrStauts = [[NSMutableArray alloc] init];
for (NSInteger i=0; i<arrDate.count; i++) {
dic = [[NSMutableDictionary alloc] init];
[dic setObject:@"0" forKey:STR_NUM(i)];
[arrStauts addObject:dic];
}
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return arrDate.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 40;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *identifier = @"CELL";
TableViewCell*cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (cell == nil) {
cell = [[TableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
}
cell.labTitle.text = arrDate[indexPath.row];
NSString *status = arrStauts[indexPath.row][STR_NUM(indexPath.row)];
if ([status integerValue] == 0) {
cell.optionalImage.image = [UIImage imageNamed:@"weixuanzhon"];
} else {
cell.optionalImage.image = [UIImage imageNamed:@"xuanzhon"];
}
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *status = arrStauts[indexPath.row][STR_NUM(indexPath.row)];
if ([status integerValue] == 0) {
[dic setObject:@"1" forKey:STR_NUM(indexPath.row)];
[arrStauts replaceObjectAtIndex:indexPath.row withObject:dic];
} else {
[dic setObject:@"0" forKey:STR_NUM(indexPath.row)];
[arrStauts replaceObjectAtIndex:indexPath.row withObject:dic];
}
[self refreshCell:indexPath.row withSection:0];
}
- (void)refreshCell:(NSInteger )row withSection:(NSInteger)section
{
[self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:row inSection:section]]
withRowAnimation:UITableViewRowAnimationNone];
}