TableViewCell选中一个后另外的取消选择

本文介绍了一种实现TableView中仅能单选一行的方法。通过监听TableView的选中与取消选中事件,结合NSUserDefaults来记录已选中的行,并改变行的显示状态以指示选择情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<span style="font-size:24px;">- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString *s1 = cell.textLabel.text;
    [user setObject:s1 forKey:@"selected"];
    if (indexPath.section == 2|indexPath.section == 3) {
        if (cell.accessoryType == UITableViewCellAccessoryNone) {
            cell.accessoryType = UITableViewCellAccessoryCheckmark;
            [cell setSelected:YES animated:YES];
        }
    }
}
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString *s2 = [user objectForKey:@"selected"];
    if (indexPath.section == 2|indexPath.section == 3) {
        if (s2 != cell.textLabel.text) {
            cell.accessoryType = UITableViewCellAccessoryNone;
        }
    }
}
</span>

刚解决了一个困扰了一天的难题 ,让tableview的row只能有一个被选中,选中一个后其他的取消选中
使用了

NSUserDefaults 

应该还有更简单的方法往告知!


再稍微简化点是
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.textLabel.textColor = [UIColor colorWithRed:arc4random()%256/255.0 green:arc4random()%256/255.0 blue:arc4random()%256/255.0 alpha:1];
    if (cell.selected == YES) {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    }else{
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
}
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.textLabel.textColor = [UIColor blackColor];
    if (cell.selected == NO) {
        cell.accessoryType = UITableViewCellAccessoryNone;
    }else{
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    }
}






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值