开发者

iPhone table view cell style based on cell data

I'm trying to figure out how to display a particular type of image in a cell based on the text contents of the cell. For example, this method from the tutorial book I am working with will allow me to display the star image for the first 3 cells:

- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *SimpleTableIdentifier = @"SimpleTableIdentifier";

    UITableViewCell *cell = [tableView dequeueReusable开发者_运维百科CellWithIdentifier:
                             SimpleTableIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc]
                 initWithStyle:UITableViewCellStyleDefault
                 reuseIdentifier:SimpleTableIdentifier] autorelease];
    }

     NSUInteger row = [indexPath row];
    if (row < 3) {
        UIImage *image = [UIImage imageNamed:@"star.png"];
        cell.imageView.image = image;
    }


    cell.textLabel.text = [listData objectAtIndex:row];
    cell.textLabel.font = [UIFont boldSystemFontOfSize:15];


    return cell;
}

Is there any way I can get the actual cell contents here? So For example, if the cell contained the text 'bob', i could display a different image rather than a star?


Well it seems like you can look at your listData object and decide there. So you can try something like this

- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *SimpleTableIdentifier = @"SimpleTableIdentifier";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:
                             SimpleTableIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc]
                 initWithStyle:UITableViewCellStyleDefault
                 reuseIdentifier:SimpleTableIdentifier] autorelease];
    }

     NSUInteger row = [indexPath row];
    if ([[listData objectAtIndex:row] isEqualToString:@"bob"]) {
        UIImage *image = [UIImage imageNamed:@"bob.png"];
        cell.imageView.image = image;
    }
    else if (row < 3) {
        UIImage *image = [UIImage imageNamed:@"star.png"];
        cell.imageView.image = image;
    }


    cell.textLabel.text = [listData objectAtIndex:row];
    cell.textLabel.font = [UIFont boldSystemFontOfSize:15];


    return cell;
}


Maybe you should setup a dictionary that contains the names of the people as the key for the dictionary and the image name as the value. Then you could grab the cell's text and use that as the lookup for the dictionary.


After you set the text:

if([cell.textLabel.text rangeOfString:@"bob"].location != NSNotFound) {
    UIImage *image = [UIImage imageNamed:@"bob.png"];
    cell.imageView.image = image;
}
else {
    UIImage *image = [UIImage imageNamed:@"star.png"];
    cell.imageView.image = image;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜