我有一个自定义的UICollectionViewCell
子类(MyCell
),它的界面使用Auto Layout在Interface Builder中设置。该单元格具有一个图片视图和一个标签。
现在,当我配置单元格时,我需要知道图片视图的宽度和高度。听起来很简单,但看起来似乎不可能。
在我的视图控制器中:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
MyCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MyCell" forIndexPath:indexPath];
cell.itemNumber = indexPath.item;
return cell;
}
在我的单元格子类中,我使用属性的setter来自定义单元格:
- (void)setItemNumber:(NSInteger)itemNumber {
_itemNumber = itemNumber;
self.label.text = [NSString stringWithFormat:@"%i", self.itemNumber];
// In my actual project I need to know the image view's width and hight to request an image
// of the right size from a server. Sadly, the frame is always {{0, 0}, {0, 0}}
// (same for the bounds)
NSLog(@"%@", NSStringFromCGRect(self.myImageView.frame));
}
完整的示例项目可在https://github.com/kevinrenskers/CollectionViewAutoLayoutTest找到。
问题是:我需要知道图像视图的尺寸,因为我需要请求服务器生成正确尺寸的图像。但是,图像视图的尺寸是{0,0}。
我也尝试在
-layoutSubviews
方法中进行自定义:- (void)setItemNumber:(NSInteger)itemNumber {
_itemNumber = itemNumber;
}
- (void)layoutSubviews {
if (self.myImageView.frame.size.height) {
self.label.text = [NSString stringWithFormat:@"%i", self.itemNumber];
NSLog(@"%@", NSStringFromCGRect(self.myImageView.frame));
}
}
不幸的是,这更加混乱了。该方法被调用两次,第一次帧是{{0, 0},{0, 0}},然后正确设置了帧。因此,检查高度的if语句不起作用了。但是,一旦开始滚动,错误的标签就会显示在错误的单元格中。我不明白这里发生了什么。
在示例项目中尝试该问题可能会更有意义。
设置宽度和高度约束并为其创建IBOutlets似乎是一个很好的选择,但遗憾的是,单元格没有固定的大小,图像需要随着单元格的缩小和扩大而调整大小。去掉自动布局也不是一个选项。