I have created a custom cell using the code below. I have only added a rounded button which is loaded correctly when cellForRowAtIndexPath
function called, but the images are not loaded. The only thing that I can see in my tableView is circle buttons without any image in it.
Can anyone help me to find where the problem is? Thanks
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;
}
try this:
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);
}
in cellForRowAtIndexPath
, profilePhoto
must be nil for first time. because cell layoutSubviews
will be called later where you init profilePhoto
.
And as you commented, scroll will reuse the cell which have call layoutSubviews
then cell have profilePhoto
object , so the image set in cellForRowAtIndexPath
can be seen after scroll.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.