[英]Adding UIImageView to custom UITableViewCell
我似乎无法将此imageview添加到我的自定义uitableviewcell类,我无法弄明白。 这是我的代码:
- (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];
}
在调试器中,我注意到,一旦我将imageview添加为contentview的子视图,如果有帮助,框架将被重新分配给(0,0,0,0)。 我真的不知道最近会发生什么。 如果有人有任何建议,那将是很棒的。 我也尝试将imageview直接添加到单元格的视图本身,但无济于事。 (而且我非常肯定那是错的)。
Tahnks!
您不应该在init
的单元格方法中设置图像。 你需要将它分开。
实现layoutSubviews
方法并检查是否有任何区别。 它应该解决这个问题。
- (void)layoutSubviews
{
videoImageView.frame = CGRectMake(5, 5, 310, 120);
}
更新:
尝试从init
方法更改layoutCell
方法。 而是在tableview的cellForRowAtIndexPath
方法[cell layoutCell]
其称为[cell layoutCell]
。 这将确保即使在重新加载时调用dequeureuse,它也会正确设置UIImage和frame。 你可以添加self.videoImageView = [[UIImageView alloc] initWithFrame:CGRectMake(5, 5, 310, 120)] ;
在你的init
方法中。
- (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];
}
在cellForRowAtIndexPath
,
//create cell
[cell layoutCell];
return cell;
您分配self.videoImageView,然后将self.imageView添加到contentView(似乎是错误输入)。 您也可以像其他人一样建议将您的UI init方法移动到initWithStyle之外的其他位置。 那会有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.