2011-06-15 173 views
3

我试图自定义一个UITableViewCell以“漂亮”的应用程序,我遇到了麻烦。我的代码:自定义UITableViewCell

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
UIImage *rowBackground; 
UIImage *selectionBackground; 
NSInteger sectionRows = [tableView numberOfRowsInSection:[indexPath section]]; 
NSInteger row = [indexPath row]; 

static NSString *CellIdentifier = @"Cell"; 

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

if (cell == nil) { 
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; 
} 

if (row == 0 && row == sectionRows - 1) { 
    rowBackground = [UIImage imageNamed:@"topAndBottomRow.png"]; 
    selectionBackground = [UIImage imageNamed:@"topAndBottomRowSelected.png"]; 
    NSLog(@"topAndBottom"); 
} 
else if (row == 0) { 
    rowBackground = [UIImage imageNamed:@"topRow.png"]; 
    selectionBackground = [UIImage imageNamed:@"topRowSelected.png"]; 
    NSLog(@"topRow"); 
} 
else if (row == sectionRows - 1) { 
    rowBackground = [UIImage imageNamed:@"bottomRow.png"]; 
    selectionBackground = [UIImage imageNamed:@"bottomRowSelected.png"]; 
    NSLog(@"bottomRow"); 
} else { 
    rowBackground = [UIImage imageNamed:@"middleRow.png"]; 
    selectionBackground = [UIImage imageNamed:@"middleRowSelected.png"]; 
    NSLog(@"middleRow"); 
} 

((UIImageView *)cell.backgroundView).image = rowBackground; 
((UIImageView *)cell.selectedBackgroundView).image = selectionBackground; 

NSString *cellValue = [[listOfItems objectAtIndex:indexPath.row] description]; 
cell.textLabel.text = cellValue; 

return cell;     
} 

它选择合适的图像,如图控制台日志,但是我有两个问题: 1.设置(cell.backgroundView)图像配不起作用 2.设置( cell.selectedBackgroundView)错误图像配带出来: - [UITableViewCellSelectedBackground setImage:]:无法识别的选择发送到实例0x4b90670

我可以找到有关的UIView这个在谷歌的问题,但还没有找到关于一个UITableViewCell任何提示。帮帮我?

回答

4

有一些不兼容性 - 没有可以设置的官方背景图像,IIRC,只有背景UIView。如果你想要的是一个UIImageView,你必须做到这一点。

所以,相反,你必须手动设置单元格的backgroundView是一个空白的UIImageView *当你创建的细胞,例如:

cell.backgroundView = [[[UIImageView alloc] init] autorelease]; 

...然后你就可以设定图像时。

+0

那么,这可以看到背景图像的边缘,但带有标签的区域仍然不显示它。我想我需要回到方形1,因为它似乎是我用来试图做到这一点的教程是3.0以前,这些方法在3.0和4.x中发生了显着变化... – John 2011-06-16 00:00:32

+2

实际上, ,一旦我将cell.textLabel.background颜色设置为clearColor。 – John 2011-06-16 00:07:31