2011-10-15 129 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,但它從來沒有爲我工作。所以我通過這種方式改變了我的想法。

相關問題