如何在UITableView单元格中设置背景图像?

时间:2011-10-15 05:01:12

标签: iphone objective-c xcode

我已创建自定义单元格。我有带有分组样式的表视图。现在我想将Backgroung图像放到不同部分的每个单元格。如何设置自定义单元格的背景图像。 以下是创建自定义单元格的代码。

UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 305, 90)];

// view.backgroundColor = [UIColor darkGrayColor];

UIImageView *imageV = [[UIImageView alloc] initWithFrame:CGRectMake(11, 9, 61, 55)];
// NSLog(@"imageArray%@",[play.imageArray count]);
NSString *img=[play.imageArray objectAtIndex:indexPath.row];
NSLog(@"img=%@",img);
imageV.image = [UIImage imageNamed:img];
[view addSubview:imageV];
[imageV release];

UILabel *lblAchievementName = [[UILabel alloc] initWithFrame:CGRectMake(90, 10, 168, 21)];
lblAchievementName.text = [play.listData objectAtIndex:indexPath.row];
lblAchievementName.backgroundColor=[UIColor clearColor];

lblAchievementName.textColor=[UIColor orangeColor];
[lblAchievementName setFont:[UIFont fontWithName:@"Arial Black" size:16.5]];

[view addSubview:lblAchievementName];
[lblAchievementName release]


[cell.contentView addSubview:view];

return cell;

现在如何为此自定义视图设置背景图像?

4 个答案:

答案 0 :(得分:21)

您可以尝试使用此代码来帮助您。

将此代码放在 cellForRowAtIndexPath 方法

   UIImageView *av = [[UIImageView alloc] initWithFrame:CGRectMake(20, 20, 277, 58)];
    av.backgroundColor = [UIColor clearColor];
    av.opaque = NO;
    av.image = [UIImage imageNamed:@"categorytab1.png"];
    cell.backgroundView = av;

答案 1 :(得分:3)

您可以在不同的部分使用以下代码来处理不同的图像。

UIImageView *imageV = [[UIImageView alloc] initWithFrame:CGRectMake(11, 9, 61, 55)];
// NSLog(@"imageArray%@",[play.imageArray count]);
NSString *img=[play.imageArray objectAtIndex:indexPath.row];
NSLog(@"img=%@",img);
if (indexPath.section == 0) {
    imageV.image = [UIImage imageNamed:img0];
}
else if (indexPath.section == 1) {
    imageV.image = [UIImage imageNamed:img1];
}
else if (indexPath.section == 2) {
    imageV.image = [UIImage imageNamed:img2];
}

[view addSubview:imageV];
[imageV release];

答案 2 :(得分:2)

设置通过setBackground查看方法。从需要Image的ImageView中将其设置为,

[cell setBackgroundView:urBgImgView];

答案 3 :(得分:0)

我宁愿添加CALayer或UIImageView作为背景视图。因为我曾经设置过背景颜色,但它从来没有为我工作过。所以我改变了主意。