您的位置:首页 > 移动开发 > IOS开发

iOS TableView实现单选checkmark功能

2014-08-28 15:56 901 查看
相信大家在做项目时有遇到需要实现这种功能---实现单选某一个cell表示选中

这个功能的实现只需要在两个方法中code即可

首选我们公开一个属性

@property(nonatomic,strong)NSIndexPath *lastPath;并且对其synthesize

主要是用来接收用户上一次所选的cell的indexpath

第一步:在cellForRowAtIndexPath:方法中实现如下代码

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

NSInteger row = [indexPath row];

NSInteger oldRow = [lastPath row];

if (row == oldRow && lastPath!=nil) {

cell.accessoryType = UITableViewCellAccessoryCheckmark;

}else{

cell.accessoryType = UITableViewCellAccessoryNone;

}

}

第二步:在didSelectRowAtIndexPath:中实现如下代码

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{ 

int newRow = [indexPath row];

int oldRow = (lastPath !=nil)?[lastPath row]:-1;

if (newRow != oldRow) {

UITableViewCell *newCell = [tableView cellForRowAtIndexPath:indexPath];

newCell.accessoryType = UITableViewCellAccessoryCheckmark;

UITableViewCell *oldCell = [tableView cellForRowAtIndexPath:lastPath];

oldCell.accessoryType = UITableViewCellAccessoryNone;

lastPath = indexPath;

}

[tableView deselectRowAtIndexPath:indexPath animated:YES];

}

Ok,可以收工了,这样实现之后的效果是每次单击一个cell会做一个选中的标志并且托动表视图时也不会出现checkmark的复用

希望对初学者有帮助到!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: