2011-10-15 94 views
4

我已创建自定义单元格。并且我有分组样式的表格视图。现在,我想将背景图像放到不同部分的每个单元格中。如何设置自定义单元格的背景图像。 这里是创建自定义单元格的代码。如何在UITableView单元格中设置背景图像?

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; 

现在如何设置这个自定义视图的背景图像?

+0

你的表格视图中有多少部分? –

+1

看看这个我以前的答案 http://stackoverflow.com/questions/6329832/uitableview-cell-with-background-image/6330427#6330427 –

回答

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; 
+3

未来的访问者 - 当使用分组的UITableView风格时,该方法将移除一些人可能需要的边界。为了避免这样做:[cell setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@“categorytab1.png”]]]; – pnizzle

+0

使backgroundView透明是没有用的,因为没有任何背后的东西。最好这样做: 'cell.textLabel.opaque = NO; cell.textLabel.backgroundColor = [UIColor clearColor];' – MacMark

+0

您可能想要在init方法中调用[UIImage imageNamed:...](initWithStyle :,如果您使用的是故事板原型单元格,initWithCoder :),以便你不会在整个地方分配新的图像。 –

2

设置直通setBackgroundView method.Form的ImageView的与乌尔需要的图像A和设置为,

[cell setBackgroundView:urBgImgView]; 
+0

我可以设置一个图像作为tableView背景,而不是单个细胞的tableView –

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]; 
0

我宁愿添加一个CALayer或UIImageView作为背景视图。因为我曾经设置BackgroundColor,但它从来没有为我工作。所以我通过这种方式改变了我的想法。

相关问题