UITableViewCell自定义 - 更改背景

时间:2011-09-19 17:02:40

标签: iphone uitableview xcode4

我确信这是一个被问及回答的问题,但我似乎无法找到我需要的东西。我试图自定义我的UITableView的背景,所以为了做到这一点,我创建了一个UITableViewCell的子类,并用IB构建了我的自定义单元格。我成功地将自定义单元格连接到表格视图,因此我得到的单元格显示出来。我正在尝试更改每个单元格的背景,所以这是我使用的:

if(row == 1){
    rowBackground = [UIImage imageNamed:@"VehicleExpenses_button.png"];
    selectionBackground = [UIImage imageNamed:@"VehicleExpenses_button_selected.png"];
    ((UIImageView *)cell.backgroundView).image = rowBackground;
  //  ((UIImageView *)cell.selectedBackgroundView).image = selectionBackground;
}

中的

(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

我的Controller类的方法。我检查了调试器,代码中的所有行都被调用了......

有什么想法吗?

这是整个方法:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"HomeViewCell";
    static NSString *CellNib = @"HomeViewCell";

    UIImage *rowBackground;
    UIImage *selectionBackground;

    NSInteger row = [indexPath row];


    UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:CellNib owner:self options:nil];
        cell = (UITableViewCell *)[nib objectAtIndex:0];
    }

    if(row == 1){

        rowBackground = [UIImage imageNamed:@"VehicleExpenses_button.png"];
        selectionBackground = [UIImage imageNamed:@"VehicleExpenses_button_selected.png"];
        ((UIImageView *)cell.backgroundView).image = rowBackground;
      //  ((UIImageView *)cell.selectedBackgroundView).image = selectionBackground;
    }

    // perform additional custom work...

    return cell;
}

3 个答案:

答案 0 :(得分:2)

也许我错了,但我没有看到你将backgroundView初始化为UIImageView。以下是我将添加到创建单元格的行中的内容:

UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:CellNib owner:self options:nil];
        cell = (UITableViewCell *)[nib objectAtIndex:0];
        cell.backgroundView = [[[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, tableView.bounds.size.width, cellHeight)] autorelease];
        cell.selectedBackgroundView = [[[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, tableView.bounds.size.width, cellHeight)] autorelease];
    }

注意:将“cellHeight”替换为您想要的高度。

我希望这会有所帮助。

答案 1 :(得分:0)

您可以使用:

UIImageView *cellBackGround = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"selectedRow.png"]];
[[tableView cellForRowAtIndexPath:indexPath] setBackgroundView:cellBackGround];
[cellBackGround release];

答案 2 :(得分:0)

小问题。不要投射和设置backgroundViewselectedBackgroundView的图片属性,而是将它们设置为从图片中创建的UIImageView

cell.backgroundView = [[[UIImageView alloc] initWithImage:rowBackground] autorelease];
cell.selectedBackgroundView = [[[UIImageView alloc] initWithImage:selectionBackground] autorelease];