单选的效果大概就是这样,如果想设置右边的accessoryType属性,更改对应的UITableViewCellAccessoryType参数即可。
1.先定义一个NSIndexPath 用于保存最后一次选中的组行
NSIndexPath * _lastSelectIndexPath;
2.cell的代理方法
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;{
UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
if(cell == nil){
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
cell.backgroundColor = [UIColor whiteColor];
cell.textLabel.font = [UIFont systemFontOfSize:12];
}
if([_lastSelectIndexPath isEqual:indexPath]){
//设置选中图片
cell.imageView.image = [UIImage imageNamed:@"icon_ssselected"];
}else {
//设置未选中图片
cell.imageView.image = [UIImage imageNamed:@"icon_unselected"];
}
cell.textLabel.text = [NSString stringWithFormat:@"Cell%ld",indexPath.row];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath;{
UITableViewCell * lastSelectCell = [tableView cellForRowAtIndexPath: _lastSelectIndexPath];
if (lastSelectCell != nil) {
lastSelectCell.imageView.image = [UIImage imageNamed:@"icon_unselected"];
}
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
cell.imageView.image = [UIImage imageNamed:@"icon_ssselected"];
_lastSelectIndexPath = indexPath;
}
多选,其实和单选差不多,只是将用于保存最后一次选中的NSIndexPath 换成数组就行了
1.定义一个数组用于保存选中的NSIndexPath
NSMutableArray * _selectArr;
数组记得初始化
2.cell的代理方法
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;{
UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
if(cell == nil){
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
cell.backgroundColor = [UIColor whiteColor];
cell.textLabel.font = [UIFont systemFontOfSize:12];
}
if([_selectArr containsObject:indexPath]){
//设置选中图片
cell.imageView.image = [UIImage imageNamed:@"icon_ssselected"];
}else {
//设置未选中图片
cell.imageView.image = [UIImage imageNamed:@"icon_unselected"];
}
cell.textLabel.text = [NSString stringWithFormat:@"Cell%ld",indexPath.row];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath;{
UITableViewCell * cell = [tableView cellForRowAtIndexPath:indexPath];
if([_selectArr containsObject:indexPath]){
[_selectArr removeObject:indexPath];
cell.imageView.image = [UIImage imageNamed:@"icon_unselected"];
}else {
[_selectArr addObject:indexPath];
cell.imageView.image = [UIImage imageNamed:@"icon_ssselected"];
}
}