在自定义TableViewCell上设置图像

时间:2012-10-25 03:15:02

标签: objective-c ios xcode uitableview

我想知道如何将图像放在自定义单元格的背景上

使用的代码就是这个,但是这会将所有表设置为相同的图像 我希望每个单元格都有自己的背景,具体取决于谁是邮件所有者 我希望你能帮我这个杀了我!

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

    UITableViewCell *cell = (UITableViewCell *)[self.messageList dequeueReusableCellWithIdentifier:@"ChatListItem"];
    if (cell == nil) {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"ChatListItem" owner:self options:nil];
        cell = (UITableViewCell *)[nib objectAtIndex:0];
    }

    NSDictionary *itemAtIndex = (NSDictionary *)[messages objectAtIndex:indexPath.row];
    UILabel *textLabel = (UILabel *)[cell viewWithTag:1];
    textLabel.text = [itemAtIndex objectForKey:@"text"];
    UILabel *userLabel = (UILabel *)[cell viewWithTag:2];
    userLabel.text = [itemAtIndex objectForKey:@"user"];

    if(usernameText=userLabel){
        UIImageView* img = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"chat2@2x.png"]];
        [cell setBackgroundView:img];
        [img release];        
    }
    else{
        UIImageView* img = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"chat1@2x.png"]];
        [cell setBackgroundView:img];
        [img release];

    }

    return cell;
}

2 个答案:

答案 0 :(得分:3)

这条线对我来说看起来不太好:

if (usernameText=userLabel)

也许应该是:

if ([usernameText isEqualToString:userLabel.text])

答案 1 :(得分:0)

试试这个,

tableView.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"chat1@2x.png"]];

或者,

cell.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@“chat1@2x.png”]];