[英]Custom cell not loading button background image
我使用下面的代码创建了一个自定义单元。 我只添加了一个圆形的按钮,当调用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;
}
尝试这个:
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
首次必须为nil。 因为单元格layoutSubviews
将在以后初始化profilePhoto
地方调用。
正如您所评论的,滚动将重用具有调用layoutSubviews
的单元格,然后具有profilePhoto
对象的单元格,因此滚动后可以看到在cellForRowAtIndexPath
设置的图像。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.