Setting cell subtitle in search table view
I am looping through data, but in this data it has two names which are exactly the same but both have a different sub topic (which is suppose to be the subtitle). So the search results show both the names with the same subtitle when they should both have different subtitles as they have different subtopics.
I thought the following code would work but it doesn't and I'm not sure what I'm doing wrong.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *kCellID = @"cellID";
static NSString *cellIdentifier = @"myCellIdentifier";
// if search is active display cell with subtitles otherwise display default
if (tableView == self.searchDisplayController.searchResultsTableView) {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyl开发者_如何学PythoneSubtitle reuseIdentifier:cellIdentifier] autorelease];
cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
cell.textLabel.numberOfLines = 0;
}
cell.textLabel.text = [self.searchFilteredListContent objectAtIndex:indexPath.row];
for(id obj in data){
if ([[obj valueForKey:@"name"] isEqualToString:[self.searchFilteredListContent objectAtIndex:indexPath.row]]) {
NSLog(@"%@",[obj valueForKey:@"subTopic"]);
cell.detailTextLabel.text = [obj valueForKey:@"subTopic"];
}
}
return cell;
}else{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellID];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kCellID] autorelease];
}
cell.textLabel.text = [self.topics objectAtIndex:indexPath.row];
return cell;
}
}
The NSLog(@"%@",[obj valueForKey:@"subTopic"])
shows the correct sub topics but it doesn't display those results in the subtitles on the search table view.
Thanks for your help!
Make sure you're using an appropriate UITableViewCellStyle
with this (anything but UITableViewCellStyleDefault
should thus work). The cell's style is specified when you initialize it.
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
You use the same cell Identifier for 2 different kinds of cell, which may cause some issues when dequeueing them, you should use 2 different cell identifiers.
Also, you should break out of your loop:
for(id obj in data){
if ([[obj valueForKey:@"name"] isEqualToString:[self.searchFilteredListContent objectAtIndex:indexPath.row]]) {
NSLog(@"%@",[obj valueForKey:@"subTopic"]);
cell.detailTextLabel.text = [obj valueForKey:@"subTopic"];
break;
}
}
精彩评论