在iOS中滚动时,保留TableView单元格中的按钮状态

时间:2014-01-28 12:05:22

标签: ios objective-c uitableview

我知道这里有很多类似的问题,但我没有找到解决方案。我在UITableViewCell中有一个复选框。

当我检查并向下滚动再次向上滚动时,其状态将重置,即unchecked

我知道单元格已在cellForRowAtIndexPath中显示,但在检查时如何保留其状态?

这是我试过的:

@interface ContactCheckedViewController ()
{
    UIButton *checkBox;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellId = @"CheckBoxedCell";
   // NSString *cellId = [NSString stringWithFormat:@"Section:%d Row:%d",indexPath.section,indexPath.row];
    CheckBoxedCellClass *cell = (CheckBoxedCellClass *)[self.tableViewContact dequeueReusableCellWithIdentifier:cellId];

    if(!cell)
    {
        NSArray *nib;
        if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
        {
            nib = [[NSBundle mainBundle] loadNibNamed:@"CheckBoxedCellClass" owner:self options:nil];
        }
        else if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
        {
            nib = [[NSBundle mainBundle] loadNibNamed:@"CheckBoxedCellClass_iPad" owner:self options:nil];
        }
            for (id object in nib)
            {
                if([object isKindOfClass:[CheckBoxedCellClass class]])
                {
                    cell = (CheckBoxedCellClass *)object;
                    break;
                }
            }

            cell = [nib objectAtIndex:0];

     }

        SaveCheckBoxedView *saveContact;
        if(isFiltered == YES) //Handling UISearchbar
        {
            saveContact = [filterdArray objectAtIndex:indexPath.row];
            cell.nameLabel.text = saveContact.nameString;
        }
        else
        {
            saveContact = [mutableArray objectAtIndex:indexPath.row];
            cell.nameLabel.text = [[objectsForCharacters objectForKey:[arrayOfCharacters objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row];
        }
    cell.companyLabel.text = saveContact.companyString;
        cell.invIdLabel.text = [NSString stringWithFormat:@"%@", saveContact.invitId];
    //handling check box

    NSInteger rowNumber = 0;
    for(NSInteger i = 0; i < indexPath.section ; i++)
    {
        rowNumber += [self tableView:self.tableViewContact numberOfRowsInSection:i];
    }

    rowNumber += indexPath.row;


    //UIButton *checkBox;
    if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
    {
        checkBox = [[UIButton alloc]initWithFrame:CGRectMake(7, 8, 30, 30)];
    }
    else
    {
        checkBox = [[UIButton alloc]initWithFrame:CGRectMake(15, 13, 30, 30)];
    }



    [checkBox setImage:[UIImage imageNamed:@"checkBox.png"] forState:UIControlStateNormal];
    [checkBox addTarget:self action:@selector(checkBoxClicked:event:) forControlEvents:UIControlEventTouchUpInside];


    // handle check box view reset when scrolled


    BOOL buttonPressed = [[self.boolArray objectAtIndex:rowNumber] boolValue];
    [checkBox setSelected:buttonPressed];
    if(buttonPressed)
    {
        [checkBox setImage:[UIImage imageNamed:@"checkBoxMarked.png"] forState:UIControlStateNormal];
    }
    else
    {
        [checkBox setImage:[UIImage imageNamed:@"checkBox.png"] forState:UIControlStateNormal];
    }

    checkBox.tag = rowNumber;
    [cell.contentView addSubview:checkBox];

    return cell;
}


-(void)checkBoxClicked:(id)sender event:(id)event
{
    NSSet *touches = [event allTouches];
    UITouch *touch = [touches anyObject];
    CGPoint currentTouchPosition = [touch locationInView:self.tableViewContact];
    NSIndexPath *indexPath = [self.tableViewContact indexPathForRowAtPoint: currentTouchPosition];
    NSLog(@"value of indexPath.section %d ,indexPath.row %d",indexPath.section,indexPath.row);

    UIButton *tappedButton = (UIButton*)sender;
    NSLog(@"Tag number = %d", [sender tag]);

    if([tappedButton.currentImage isEqual:[UIImage imageNamed:@"checkBox.png"]])
    {
        [sender  setImage:[UIImage imageNamed: @"checkBoxMarked.png"] forState:UIControlStateNormal];
        NSUserDefaults *buttonDefault = [NSUserDefaults standardUserDefaults];
        [buttonDefault setBool:YES forKey:@"CHECKMARKEDKEY"];

        //add values in boolArray to retain button state 
        [boolArray replaceObjectAtIndex:[sender tag] withObject:[NSNumber numberWithBool:YES]];

        if(isFiltered == YES)
        {
            NSString *addId = [filteredArrayOfIds objectAtIndex:indexPath.row];
            NSLog(@"filterd id = %@", addId); //get filtered array here
            [arrayOfIds addObject:addId];
        }
        else
        {
            NSString *finalIntId = [mutableArrayOfIds objectAtIndex:tappedButton.tag];
            NSLog(@"Tagged checked button id = %@", finalIntId);
            [arrayOfIds addObject:finalIntId];
        }

    }
    else
    {
        [sender setImage:[UIImage imageNamed:@"checkBox.png"]forState:UIControlStateNormal];
        NSLog(@"UnChecked");
        NSUserDefaults *buttonDefault = [NSUserDefaults standardUserDefaults];
        [buttonDefault setBool:NO forKey:@"CHECKMARKEDKEY"];

        [boolArray replaceObjectAtIndex:[sender tag] withObject:[NSNumber numberWithBool:NO]];

        if(isFiltered == YES)
        {
            [arrayOfIds removeObjectIdenticalTo:[filteredArrayOfIds objectAtIndex:tappedButton.tag]];
        }
        else
        {
            [arrayOfIds removeObjectIdenticalTo:[mutableArrayOfIds objectAtIndex:tappedButton.tag]];
        }
    }
    NSLog(@"bool array = %@", boolArray);

}

请让我知道我的代码中应该更改什么。任何有关示例代码的帮助都将受到赞赏。

感谢。

3 个答案:

答案 0 :(得分:1)

为此你必须维护NSMutableArray和boolean。让我们假设它的

NSMutableArray *selectedRows; BOOL isRowSelected;

然后在'didSelectRowAtIndexPath'中你必须使bool值'YES'和'NO'

UIButton *btn = (UIButton *)[cell viewWithTag://your button tag]; //your button instance

if(isRowSelected){

    // set button checked
    isRowSelected = NO;
    [selectedRows addObject:indexPath];
}
else{

    // set button checked
    isRowSelected = YES;
    [selectedRows removeObject:indexPath];
}

[tableView deselectRowAtIndexPath:indexPath animated:YES];`

最后在'cellForRowAtIndexPath'

// Mentain state for UIButton.
if([selectedRows containsObject:indexPath])
    // your button state : checked
else
    // your button state : unchecked

答案 1 :(得分:0)

试试这个,

而不是boolArray使用NSMutableDictionary *boolDict

//init this in viewDidLoad
NSMutableDictionary *boolDict = [[NSMutableDictionary alloc] init];

cellForRowAtIndexPath :中使用

BOOL buttonPressed = [[boolDict objectForKey:[NSString stringWithFormat:@"%d", rowNumber]] boolValue];

checkBoxClicked :中使用

[boolDict setObject:[NSNumber numberWithBool:YES] forKey:[NSString stringWithFormat:@"%d", [sender tag]]];

[boolDict setObject:[NSNumber numberWithBool:NO] forKey:[NSString stringWithFormat:@"%d", [sender tag]]];

答案 2 :(得分:0)

static NSString *cellId = @"CheckBoxedCell";

CheckBoxedCell更改为您的手机类名称。

我希望它的工作正常