Ios 使用自定义UITableViewCell时,imageview帧为零
我创建了一个自定义UITableViewCell,但希望使用该单元格中的标准UIImageView 我注意到帧总是归零,这给我带来了问题Ios 使用自定义UITableViewCell时,imageview帧为零,ios,objective-c,uitableview,uiimageview,Ios,Objective C,Uitableview,Uiimageview,我创建了一个自定义UITableViewCell,但希望使用该单元格中的标准UIImageView 我注意到帧总是归零,这给我带来了问题 @implementation MyCustomCell - (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier { // the style is "default" style self = [super ini
@implementation MyCustomCell
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
// the style is "default" style
self = [super initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
// I need to override the cells image
if (self) {
self.imageView.image = [UIImage imageNamed:@"MyImageToUseInThisCell"]; // The image view frame is {0,0,0,0}
}
return self;
}
在
-initWithStyle:reuseIdentifier:
中不会得到任何帧大小,因为单元格尚未加载,这意味着子视图尚未创建(即为nil
),因此帧大小为0。
即使对于viewController
,也不会在-initWithNibName:
方法中获得帧大小
你最好是:
-layoutSubviews
在-awakeFromNib
中设置初始属性(或直接通过IB)
无论如何,试试这个:
//does this method even run? it shouldn't for a custom UITableViewCell
//unless you've mixed up things unnecessarily
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
NSLog(@"initWithStyle -- %@",self.myImageView);
}
return self;
}
//do frame related stuff here
-(void)layoutSubviews
{
//fyi: this method is called anytime any frame changes
NSLog(@"layoutSubviews -- %@",self.myImageView);
}
- (void)awakeFromNib
{
//fyi: this method is called when the view is pulled from the IB
// Initialization code
NSLog(@"awakeFromNib -- %@",self.myImageView);
//do you thang here
[self.myImageView setImage:[UIImage imageNamed:@"MyImageToUseInThisCell"]];
}
问题似乎在于,当使用重用标识符和索引路径对自定义单元格进行排队时,自定义单元格基类不会设置这些属性。文档中没有提到这一点,这是非常不幸的。在-initWithStyle:
中设置一个断点。它符合这个方法吗?另外,请将您的-cellForRowAtIndexPath:
(为了清楚起见)包括在内。即使它确实点击了-initWithStyle:
,它也不会返回任何帧大小,因为单元格尚未加载,这意味着子视图尚未创建(即为nil
)。您最好在-layoutSubviews
中使用特定于帧的相关内容,至于设置图像属性,我会在-awakeFromNib
中进行设置。。。我不能完全确定您的问题的具体内容,所以我只是把它放在那里(虽然您看起来应该知道),但您必须手动将UIImageView
对象拖动到自定义的UITableViewCell
上。自定义UITableViewCell中没有标准的UIImageView
,它的大小为零well@AvnerBarr:您是否已通过IB拖动并连接了UIImageView
对象?(在我的示例中,它被称为myImageView
)@avnerbar。那锡伯呢?将-cellForRowAtIndexPath:
方法添加到您的问题中以获得澄清似乎问题在于,当使用重用标识符和单元标识符对自定义单元进行求值时,该单元不会设置我怀疑的那些属性。