如何从tableview单元格中搜索数据?

时间:2011-11-30 06:30:10

标签: iphone ios uitableview uilabel uisearchbardelegate

我有一个UITableview控制器,用于表示获取的XML数据。为了表示这些数据,我使用了五个UILabel。现在,我必须在searchbar的顶部添加UITableview。因此,我以编程方式添加了searchbar

现在我使用搜索定理来搜索UITableview的搜索数据。但它不起作用。我可以search来自UItableview的数据,UItableviewcell中只有一个文字没有任何UIlabel或其他内容,但在我的UItableviewcell单元格中只有5 UILabel这就是为什么search来自UItableviewcell的{​​{1}}数据变得困难的原因。为了理解我正在附加我的代码,我在tableview单元格中表示我的XML数据。

这是我在UITableviewCell ...

中的XML数据表示
 static NSString *MyIdentifier = @"MyIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:MyIdentifier] autorelease];
    cell.textLabel.font = [UIFont fontWithName:@"Helvetica" size:15.0];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"arrow.png"]];
    cell.accessoryView = imageView;
    cell.accessoryType = UITableViewCellSelectionStyleNone;
    tableView.separatorColor = [UIColor clearColor];
    tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;

    cellView = [[[UIView alloc] initWithFrame:CGRectMake(5,8,290, 120)] autorelease];
    cellView.backgroundColor = [UIColor clearColor];
    cellView.tag =10;
    [cell.contentView addSubview:cellView];

    imgView = [[UIImageView alloc] initWithFrame:CGRectMake(2, 40, 48, 48)];
    imgView.image = [UIImage imageNamed:@"productbox.png"];
    imgView.layer.borderColor = [UIColor blackColor].CGColor;
    imgView.layer.borderWidth = 2.0;
    imgView.tag = 5;
    [cellView addSubview:imgView];

    CGRect idLabelRect = CGRectMake(65, 0, 190, 18);
    idLabel = [[[UILabel alloc] initWithFrame:idLabelRect] autorelease];
    idLabel.textAlignment = UITextAlignmentLeft;
    idLabel.textColor = [UIColor blackColor];
    idLabel.font = [UIFont systemFontOfSize:12];
    idLabel.backgroundColor = [UIColor clearColor];
    idLabel.layer.borderColor = [UIColor grayColor].CGColor;
    idLabel.tag = 0;

    CGRect statusRect = CGRectMake(65, 22, 190, 22);
    statusLabel = [[[UILabel alloc] initWithFrame:statusRect] autorelease];
    statusLabel.textAlignment = UITextAlignmentLeft;
    statusLabel.textColor = [UIColor blackColor];
    statusLabel.font = [UIFont systemFontOfSize:12];
    statusLabel.backgroundColor = [UIColor clearColor];
    statusLabel.layer.borderColor = [UIColor grayColor].CGColor;
    statusLabel.tag = 1;

    CGRect orderDateRect = CGRectMake(65, 48, 190, 22);
    orderDate = [[[UILabel alloc] initWithFrame:orderDateRect] autorelease];
    orderDate.textAlignment = UITextAlignmentLeft;
    orderDate.textColor = [UIColor blackColor];
    orderDate.font = [UIFont systemFontOfSize:12];
    orderDate.backgroundColor = [UIColor clearColor];
    orderDate.layer.borderColor = [UIColor grayColor].CGColor;
    orderDate.tag = 2;

    CGRect byRect = CGRectMake(65, 75, 190, 22);
    byLabel = [[[UILabel alloc] initWithFrame:byRect] autorelease];
    byLabel.textAlignment = UITextAlignmentLeft;
    byLabel.textColor = [UIColor blackColor];
    byLabel.font = [UIFont systemFontOfSize:12];
    byLabel.backgroundColor = [UIColor clearColor];
    byLabel.layer.borderColor = [UIColor grayColor].CGColor;
    byLabel.tag = 3;

    CGRect totalRect = CGRectMake(65, 98, 190, 22);
    totalLabel = [[[UILabel alloc] initWithFrame:totalRect] autorelease];
    totalLabel.textAlignment = UITextAlignmentLeft;
    totalLabel.textColor = [UIColor blackColor];
    totalLabel.font = [UIFont systemFontOfSize:12];
    totalLabel.backgroundColor = [UIColor clearColor];
    totalLabel.layer.borderColor = [UIColor grayColor].CGColor;
    totalLabel.tag = 4;

    [cellView addSubview:idLabel];
    [cellView addSubview:statusLabel];
    [cellView addSubview:orderDate];
    [cellView addSubview:byLabel];
    [cellView addSubview:totalLabel];
}


if(searching == YES){

    //[cell setText:[tableData objectAtIndex:indexPath.row]];

    cell.textLabel.text = [tableData objectAtIndex:indexPath.row];
}
else{

    cellView = (UIView *)[cell.contentView viewWithTag:10];
    idLabel = (UILabel *)[cellView viewWithTag:0];
    statusLabel = (UILabel *)[cellView viewWithTag:1];
    orderDate = (UILabel *)[cellView viewWithTag:2];
    byLabel = (UILabel *)[cellView viewWithTag:3];
    totalLabel = (UILabel *)[cellView viewWithTag:4];
    imgView = (UIImageView *)[cellView viewWithTag:5];
    if(pendingOrder == NO && todaysOrder == NO){
        idLabel.text = [NSString stringWithFormat:@"Order Id: %@",[[records objectAtIndex:indexPath.section] objectAtIndex:0]];
        statusLabel.text = [NSString stringWithFormat:@"Status: %@",[[records objectAtIndex:indexPath.section] objectAtIndex:1]];
        orderDate.text = [NSString stringWithFormat:@"Date: %@",[[records objectAtIndex:indexPath.section] objectAtIndex:2]];
        byLabel.text =[NSString stringWithFormat:@"By: %@",[[records objectAtIndex:indexPath.section] objectAtIndex:3]];
        totalLabel.text =[NSString stringWithFormat:@"Total: %@",[[records objectAtIndex:indexPath.section] objectAtIndex:4]];
    }
    else if(pendingOrder == YES && todaysOrder == NO){
        idLabel.text = [NSString stringWithFormat:@"Order Id: %@",[[pendingRecords objectAtIndex:indexPath.section] objectAtIndex:0]];
        statusLabel.text = [NSString stringWithFormat:@"Status: %@",[[pendingRecords objectAtIndex:indexPath.section] objectAtIndex:1]];
        orderDate.text = [NSString stringWithFormat:@"Date: %@",[[pendingRecords objectAtIndex:indexPath.section] objectAtIndex:2]];
        byLabel.text =[NSString stringWithFormat:@"By: %@",[[pendingRecords objectAtIndex:indexPath.section] objectAtIndex:3]];
        totalLabel.text =[NSString stringWithFormat:@"Total: %@",[[pendingRecords objectAtIndex:indexPath.section] objectAtIndex:4]];
    }
}
return cell;
}

这个搜索代表.....

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar{
searching = YES;
// only show the status bar’s cancel button while in edit mode
sBar.showsCancelButton = YES;
sBar.autocorrectionType = UITextAutocorrectionTypeNo;
// flush the previous search content
[tableData removeAllObjects];
}
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar{
searching = NO;
sBar.showsCancelButton = NO;
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
[tableData removeAllObjects];// remove all data that belongs to previous search
if([searchText isEqualToString:@""] && searchText==nil){
    [tableview reloadData];
    return;
}
NSInteger counter = 0;
for(NSString *name in dataSource)
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];
    NSRange r = [name rangeOfString:searchText];
    if(r.location != NSNotFound)
    {
        if(r.location== 0)//that is we are checking only the start of the names.
        {
            [tableData addObject:name];
        }
    }
    counter++;
    [pool release];
}
[tableview reloadData];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
// if a valid search was entered but the user wanted to cancel, bring back the main list content
[tableData removeAllObjects];
searching = NO;

[tableData addObjectsFromArray:dataSource];
@try{
    searching = NO;
    [tableview reloadData];
}
@catch(NSException *e){
}
[sBar resignFirstResponder];
sBar.text = @"";
}

// called when Search (in our case “Done”) button pressed
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
[sBar resignFirstResponder];
}

要获得更多帮助,我还要附上viewDidLoad ....

//Add the search bar
sBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0,0,320,50)];
sBar.delegate = self;
searching = NO;
[self.view addSubview:sBar];

tableview.dataSource = self;
tableview.delegate = self;

//initialize the two arrays; datasource will be initialized and populated by appDelegate
searchData = [[NSMutableArray alloc] init];
tableData = [[NSMutableArray alloc] init];


[tableData addObjectsFromArray:dataSource];//on launch it should display all the records 

修改

这是我numberOfSectionsInTableViewnumberOfRowsInSection ...

的编辑部分
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
if(searching == YES){
    searching = NO;
    sectionCount = [tableData count];
}
else {
    if(pendingOrder == NO && todaysOrder == NO){
        sectionCount = [records count];
        NSLog(@"section cout: %d",sectionCount);
    }
    else if(pendingOrder == YES && todaysOrder == NO){

        //Total pending order counting
        sectionCount = [pendingRecords count];
        NSLog(@"section cout for pending: %d",sectionCount);
    }
    else if(pendingOrder == NO && todaysOrder == YES){      
        NSLog(@"todays order number counting");     
    }
}
return sectionCount;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 1;
}

1 个答案:

答案 0 :(得分:1)

试试这个: -

copylistofItem是NSMutableArray复制与搜索栏条件匹配的数据。

- (void) searchBarSearchButtonClicked:(UISearchBar *)theSearchBar {

    NSString *searchText = searchBar.text;
    NSMutableArray *searchArray = [[NSMutableArray alloc] init];
    int i=0
    for (NSString *str in [records objectAtIndex:indexPath.i] objectAtIndex:0])
    {
                [searchArray addObject:str];
                i++;    
    }

    for (NSString *sTemp in searchArray)
    {

        NSString *txtToSearch =[[NSString alloc] initWithString:[sTemp substringWithRange:NSMakeRange(0,[searchText length])]];


        if([[txtToSearch lowercaseString] isEqualToString:[searchText lowercaseString]])
        {
            [copyListOfItems addObject:sTemp];     
        }

    }
    [searchArray release];
    searchArray = nil;

}

我们也想知道你在numberOfSections tableView Delegate中写了什么。