使用 UISearchBar 时保留 UITableView 单元格状态 [英] Retain UITableView cell state when UISearchBar is used

查看:25
本文介绍了使用 UISearchBar 时保留 UITableView 单元格状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 UISearchBar 在 UITableView 单元格中搜索名称.UISearchBar中输入字符时如何保持单元格状态?

I am using UISearchBar to search names in UITableView cells. How to retain the cell state when charachters are entered in UISearchBar?

我在 cellForRowAtIndexPath 中分配了复选框,并假设我做出了如下面的屏幕截图所示的选择.

I allocated the checkbox in cellForRowAtIndexPath and suppose I made the selection as shown in the screenshot below.

现在,如果我用字母S"开始搜索,复选框状态为未选中",如下所示.

Now if I start searching with letter 'S', checkBox state is 'unchecked' as can be seen below.

即使在搜索时单元格被过滤",我如何保留复选框状态.我知道cellForRowAtIndexPath 每次我们在 UISearchBar 中输入文本时都会调用.下面是我的 cellForRowAtIndexPath 方法.

How do I retain the checkBox state even if the cells are "filtered" while searching. I am aware that cellForRowAtIndexPath is invoked every time when we enter text in UISearchBar. Below is my cellForRowAtIndexPath method.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //static NSString *cellId = @"CheckBoxedCell";
    NSString *cellId = [NSString stringWithFormat:@"S%1dR%1d",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];

    }

    //handling check box

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

    rowNumber += indexPath.row;

    SaveCheckBoxedView *saveContact;
    if(isFiltered == YES)
    {
        saveContact = [filterdArray objectAtIndex:indexPath.row];
        cell.nameLabel.text = saveContact.nameString;
        cell.companyLabel.text = saveContact.companyString;
    }
    else
    {
        saveContact = [mutableArray objectAtIndex:indexPath.row];
        cell.nameLabel.text = [[objectsForCharacters objectForKey:[arrayOfCharacters objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row];
        cell.companyLabel.text = [NSString stringWithFormat:@"%@", [companyArray objectAtIndex:rowNumber]];
    }

    cell.invIdLabel.text = [NSString stringWithFormat:@"%@", saveContact.invitId];

    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
    if(isFiltered == YES)
    {
        NSLog(@"filtered");
        checkBox.tag = indexPath.row;
        BOOL buttonPressed = [[boolDict objectForKey:[NSString stringWithFormat:@"%d", indexPath.row]] boolValue];
        NSLog(@"Row number = %d", indexPath.row);
        [checkBox setSelected:buttonPressed];
        if(buttonPressed)
        {
           [checkBox setImage:[UIImage imageNamed:@"checkBoxMarked.png"] forState:UIControlStateNormal];
        }
        else
        {
           [checkBox setImage:[UIImage imageNamed:@"checkBox.png"] forState:UIControlStateNormal];

        }
    }
    else
    {
        BOOL buttonPressed = [[boolDict objectForKey:[NSString stringWithFormat:@"%d", rowNumber]] boolValue];
        NSLog(@"Row number = %d", rowNumber);
        [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"];


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


        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");

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

        if(isFiltered == YES)
        {
            [arrayOfIds removeObjectIdenticalTo:[filteredArrayOfIds objectAtIndex:tappedButton.tag]];
        }
        else
        {
            [arrayOfIds removeObjectIdenticalTo:[mutableArrayOfIds objectAtIndex:tappedButton.tag]];
        }
    }
}

UISearhBar方法如下

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    searchBar.text=@"";

    [searchBar setShowsCancelButton:NO animated:YES];
    [searchBar resignFirstResponder];
    [self.tableViewContact reloadData];
    [self.tableViewContact scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
}




- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    if(searchText.length == 0)
    {
        isFiltered = NO;
    }
    else
    {
        isFiltered = YES;
        filterdArray = [[NSMutableArray alloc] init];
        filteredArrayOfIds = [[NSMutableArray alloc] init];
        for (SaveCheckBoxedView *contact in mutableArray)
        {
            NSRange nameRange = [contact.nameString rangeOfString:searchText options:NSCaseInsensitiveSearch];
            if(nameRange.location != NSNotFound)
            {
                [filterdArray addObject:contact];
                [filteredArrayOfIds addObject:contact.invitId];
            }
        }
    }
    [self.tableViewContact reloadData];
}

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{

    [searchBar setShowsCancelButton:NO animated:YES];
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [self.mySearchBar resignFirstResponder];
    [mySearchBar setShowsCancelButton:NO animated:YES];

}

- (void) searchDisplayController:(UISearchDisplayController *)controller didLoadSearchResultsTableView:(UITableView *)tableView
{
    [tableViewContact registerClass:[CheckBoxedCellClass class] forCellReuseIdentifier:@"SaveContactCellID"];
}

- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
    [filterdArray removeAllObjects];
    if(searchString.length > 0)
    {
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF contains [search] %@", self.mySearchBar.text];
        for (NSString *key in arrayOfCharacters)
        {
            NSArray *matches = [objectsForCharacters[key] filteredArrayUsingPredicate:predicate];
            [filterdArray addObjectsFromArray:matches];
        }
    }
    return YES;
}

- (void)searchDisplayControllerWillBeginSearch:(UISearchDisplayController *)controller
{
    [self.tableViewContact reloadSectionIndexTitles];
}

推荐答案

用以下代码解决了我自己的问题

Solved my own issue with the following code

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //static NSString *cellId = @"CheckBoxedCell";
    NSString *cellId = [NSString stringWithFormat:@"S%1dR%1d",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];

    }

    //set fonts
    if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
    {

        [cell.companyLabel setFont:[UIFont italicSystemFontOfSize:10.0]];
    }
    else
    {

        [cell.companyLabel setFont:[UIFont italicSystemFontOfSize:14.0]];
    }

    //handling check box

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

    rowNumber += indexPath.row;

    SaveCheckBoxedView *saveContact;
    if(isFiltered == YES)
    {
        saveContact = [filterdArray objectAtIndex:indexPath.row];
        cell.nameLabel.text = saveContact.nameString;
        cell.companyLabel.text = saveContact.companyString;
    }
    else
    {
        saveContact = [mutableArray objectAtIndex:indexPath.row];
        cell.nameLabel.text = [[objectsForCharacters objectForKey:[arrayOfCharacters objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row];
        cell.companyLabel.text = [NSString stringWithFormat:@"%@", [companyArray objectAtIndex:rowNumber]];
    }

    cell.invIdLabel.text = [NSString stringWithFormat:@"%@", saveContact.invitId];

    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



    if(isFiltered == YES)
    {
        NSLog(@"filtered");
        BOOL buttonPress = [[boolDictForSearch objectForKey:[filteredArrayOfIds objectAtIndex:indexPath.row]] boolValue];
        NSLog(@"button press = %d", buttonPress);
        [checkBox setSelected:buttonPress];
        if(buttonPress)
        {
            [checkBox setImage:[UIImage imageNamed:@"checkBoxMarked.png"] forState:UIControlStateNormal];
        }
        else
        {
            [checkBox setImage:[UIImage imageNamed:@"checkBox.png"] forState:UIControlStateNormal];

        }
        checkBox.tag = indexPath.row;
    }
    else
    {
        BOOL buttonPressed = [[boolDict objectForKey:[NSString stringWithFormat:@"%d", rowNumber]] boolValue];
        NSLog(@"button pressED = %d", buttonPressed);
        NSLog(@"Row number = %d", rowNumber);
        [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"];


        [self.boolDict setObject:[NSNumber numberWithBool:YES] forKey:[NSString stringWithFormat:@"%d", [sender tag]]];
        //[self.boolDictForSearch setObject:[NSNumber numberWithBool:YES] forKey:[NSString stringWithFormat:@"%@", saveContact.nameString]];

        if(isFiltered == YES)
        {
            NSString *addId = [filteredArrayOfIds objectAtIndex:indexPath.row];

            [self.boolDictForSearch setObject:[NSNumber numberWithBool:YES] forKey:addId];

            NSLog(@"filterd id = %@", addId); //get filtered array here
            [arrayOfIds addObject:addId];
        }
        else
        {
            NSString *finalIntId = [mutableArrayOfIds objectAtIndex:tappedButton.tag];

            [self.boolDictForSearch setObject:[NSNumber numberWithBool:YES] forKey:finalIntId];

            NSLog(@"Tagged checked button id = %@", finalIntId);
            [arrayOfIds addObject:finalIntId];
        }

    }
    else
    {
        [sender setImage:[UIImage imageNamed:@"checkBox.png"]forState:UIControlStateNormal];
        NSLog(@"UnChecked");

        [self.boolDict setObject:[NSNumber numberWithBool:NO] forKey:[NSString stringWithFormat:@"%d", [sender tag]]];
        //[self.boolDictForSearch setObject:[NSNumber numberWithBool:NO] forKey:[NSString stringWithFormat:@"%@", saveContact.nameString]];

        if(isFiltered == YES)
        {
            [arrayOfIds removeObjectIdenticalTo:[filteredArrayOfIds objectAtIndex:tappedButton.tag]];
            [self.boolDictForSearch setObject:[NSNumber numberWithBool:NO] forKey:[filteredArrayOfIds objectAtIndex:tappedButton.tag]];
        }
        else
        {
            [arrayOfIds removeObjectIdenticalTo:[mutableArrayOfIds objectAtIndex:tappedButton.tag]];
            [self.boolDictForSearch setObject:[NSNumber numberWithBool:NO] forKey:[mutableArrayOfIds objectAtIndex:tappedButton.tag]];
        }
    }
}

这篇关于使用 UISearchBar 时保留 UITableView 单元格状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆