自定义单元格不加载按钮背景图像

时间:2014-03-18 14:17:15

标签: ios objective-c uitableview tableview

我使用下面的代码创建了一个自定义单元格。我只添加了一个圆形按钮,在调用cellForRowAtIndexPath函数时正确加载,但未加载图像。我在tableView中唯一可以看到的是没有任何图像的圆形按钮。

任何人都可以帮我找到问题所在吗? 感谢

CustomCell.h

@interface CustomCell : UITableViewCell {
    UIButton *profilePhoto;
}

@property (nonatomic, retain) IBOutlet UIButton *profilePhoto;

@end

CustomCell

- (void)layoutSubviews {

    [super layoutSubviews];

    profilePhoto = [UIButton buttonWithType:UIButtonTypeCustom];
    UIColor  *borderColor = [UIColor redColor];

    profilePhoto.frame = CGRectMake(5.0, 8.0, 60.0, 60.0);
    profilePhoto.clipsToBounds = YES;
    profilePhoto.layer.cornerRadius = 30;
    profilePhoto.layer.borderColor = borderColor.CGColor;
    profilePhoto.layer.borderWidth= 1.5f;
    profilePhoto.backgroundColor = [UIColor clearColor];

    [self.contentView addSubview: profilePhoto];
}

的cellForRowAtIndexPath

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

    CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];

    if (cell == nil) {
        cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
    }

    // Set up the cell
    switch (indexPath.row) {

        case 0:
            [cell.profilePhoto setBackgroundImage:[UIImage imageNamed:@"nick.png"] forState:UIControlStateNormal];
            break;

        case 1:
            [cell.profilePhoto setBackgroundImage:[UIImage imageNamed:@"michael.png"] forState:UIControlStateNormal];
            break;

        default:
            break; 
    }
    return cell;
}

1 个答案:

答案 0 :(得分:0)

试试这个:

<强> CustomCell

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
       profilePhoto = [UIButton buttonWithType:UIButtonTypeCustom];
       UIColor  *borderColor = [UIColor redColor];
       profilePhoto.clipsToBounds = YES;
       profilePhoto.layer.cornerRadius = 30;
       profilePhoto.layer.borderColor = borderColor.CGColor;
       profilePhoto.layer.borderWidth= 1.5f;
       profilePhoto.backgroundColor = [UIColor clearColor];
       [self.contentView addSubview: profilePhoto];
    }
}

- (void)layoutSubviews {

    [super layoutSubviews];
    profilePhoto.frame = CGRectMake(5.0, 8.0, 60.0, 60.0);
}
cellForRowAtIndexPath

profilePhoto首次必须为零。因为稍后在初始化layoutSubviews的地方调用单元格profilePhoto

正如您所评论的,滚动将重用已调用layoutSubviews然后单元格具有profilePhoto对象的单元格,因此滚动后可以看到cellForRowAtIndexPath中设置的图像。