自动布局:无法获取UICollectionViewCell子视图的框架大小

5

我有一个自定义的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似乎是一个很好的选择,但遗憾的是,单元格没有固定的大小,图像需要随着单元格的缩小和扩大而调整大小。去掉自动布局也不是一个选项。

从你的代码来看,你没有初始化标签或图像视图。这是正确的吗,还是你只是省略了这个示例项目的代码? - Maarten
图片视图的大小由什么决定? - rdelmar
我正在使用一个故事板,这就是初始化imageView和label的方式。大小由自动布局确定,使用顶部、底部、左侧和右侧约束。 - Kevin Renskers
1个回答

1
最后,我在imageview上添加了顶部、右侧、底部和左侧的间距约束(到父视图),为它们添加了IBOutlets,并使用了类似以下的代码:
CGFloat height = self.contentView.bounds.size.height - self.topConstraint.constant - self.bottomConstraint.constant;
CGFloat width = self.contentView.bounds.size.width - self.leftConstraint.constant - self.rightConstraint.constant;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接