IOS:didSelectRowAtIndexPath选择单个单元格时选择多个单元格

时间:2017-07-18 13:57:29

标签: ios objective-c uitableview

我有一个UITableView,其中包含30多个UITableviewCells。

我面临的问题是,当选择行并更改单元格的accessoryType时,该行的第11行也会被修改。

我已尝试打印[indexPath row]值,但它只显示已选择的行而非另一行。

我使用以下代码:

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *simpleTableIdentifier = @"SimpleTableItem";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
    }

    cell.textLabel.font=[UIFont fontWithName: @"Arial" size: 14.0];
    cell.textLabel.lineBreakMode = NSLineBreakByWordWrapping;

.
.
.
}

请帮我解决这个问题

1 个答案:

答案 0 :(得分:1)

你需要跟踪选中的单元格,你可以使用NSMutableDictionary作为键使用IndexPath.row并将其作为一个String值,所以在你的DidSelectRow中修改字典设置Row的值="选择&# 34;并在你的CellForRow方法中检查Dictionary [indexPath.row] ==" Selected"然后将你的配件默认删除

@interface ViewController () <UITableViewDataSource,UITableViewDelegate>

@property NSMutableDictionary * dict;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    _dict = [NSMutableDictionary dictionary];
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *simpleTableIdentifier = @"SimpleTableItem";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
    }
    cell.accessoryType = UITableViewCellAccessoryNone;
    if([((NSString*)[_dict objectForKey:[NSString stringWithFormat:@"%li",(long)indexPath.row]]) isEqualToString: @"Selected"])
    {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    }
    cell.textLabel.font=[UIFont fontWithName: @"Arial" size: 14.0];
    cell.textLabel.lineBreakMode = NSLineBreakByWordWrapping;

    return cell;
}

在didSelectRowAtIndexPath方法

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString * value = (NSString*)[_dict objectForKey:[NSString stringWithFormat:@"%li",(long)indexPath.row]];

    if ([value isEqualToString:@"Selected"]){
        [_dict setValue:@"UnSelected" forKey:value];
    }else{
        [_dict setValue:@"Selected" forKey:[NSString stringWithFormat:@"%li",(long)indexPath.row]];
    }

    [tableView reloadRowsAtIndexPaths:@[indexPath,[NSIndexPath indexPathForRow:[value integerValue] inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
}

希望这有助于你

相关问题