简体   繁体   中英

Adding UIImageView to custom UITableViewCell

I can't seem to add this imageview to my custom uitableviewcell class and i can't figure it out. Here is my code:

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        // Initialization code
        [self layoutCell];
    }
    return self;
}

- (void)layoutCell
{
    self.videoImageView = [[UIImageView alloc] initWithFrame:CGRectMake(5, 5, 310, 120)];
    [self.videoImageView setImage:[UIImage imageNamed:@"myImage.jpg"]];
    [self.contentView addSubview:self.imageView];
}

In the debugger, i noticed that once i add the imageview as a subview of the contentview, the frame gets reassigned to (0,0,0,0) if that helps. I really have no idea whats going on. If anyone has any suggestions that'd be awesome. I've also tried adding the imageview directly to the cell's view itself, to no avail. (and im pretty sure thats wrong anyway).

Tahnks!

You should not set your image in init method of cell. You need to keep it separate.

Implement layoutSubviews method and check if that makes any difference. It should fix this.

- (void)layoutSubviews
{
  videoImageView.frame = CGRectMake(5, 5, 310, 120);
}

Update:

Try changing the layoutCell method from init method. Instead call it as [cell layoutCell] in cellForRowAtIndexPath method of tableview. This will make sure that even if the dequeureuse is called while reloading, it will properly set the UIImage and frame. You can just add self.videoImageView = [[UIImageView alloc] initWithFrame:CGRectMake(5, 5, 310, 120)] ; in your init method.

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        // Initialization code
        self.videoImageView = [[[UIImageView alloc] initWithFrame:CGRectMake(5, 5, 310, 120)] autorelease]; //no need of autorelease if ARC is used
    }
    return self;
}

- (void)layoutCell
{
    self.videoImageView.frame = CGRectMake(5, 5, 310, 120);
    [self.videoImageView setImage:[UIImage imageNamed:@"myImage.jpg"]];
    [self.contentView addSubview:self.videoImageView];
}

In cellForRowAtIndexPath ,

//create cell
[cell layoutCell];

return cell;

You alloc the self.videoImageView and then add a self.imageView to the contentView (seems as a mis typing). Also you can do as others suggested that move your UI init method to somewhere else than initWithStyle. That will help.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM