iOS TableView实现单选checkmark功能

相信大家在做项目时有遇到需要实现这种功能---实现单选某一个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的复用

希望对初学者有帮助到!

转载于:https://www.cnblogs.com/billy-chou/p/3941746.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值