iOS tableView 自定义单选cell 和多选cell

单选的效果大概就是这样,如果想设置右边的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"];

}

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容