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

Kev*_*ers 5 ios autolayout uicollectionviewcell

我有一个自定义的UICollectionViewCell子类(MyCell),它的界面是使用自动布局在Interface Builder中设置的.单元格具有图像视图和标签.

现在,当我配置单元格时,我需要知道图像视图的宽度和高度.听起来很简单,但看起来这是不可能的.

在我的视图控制器中:

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    MyCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MyCell" forIndexPath:indexPath];
    cell.itemNumber = indexPath.item;
    return cell;
}
Run Code Online (Sandbox Code Playgroud)

在我的单元子类中,我使用我的属性的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));
}
Run Code Online (Sandbox Code Playgroud)

可以在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));
    }
}
Run Code Online (Sandbox Code Playgroud)

可悲的是,这更加混乱了.调用该方法两次,首先帧为{{0,0},{0,0}},然后正确设置帧.因此if语句检查高度.一旦你开始滚动,错误的单元格会显示错误的标签.我不明白这里发生了什么.

示例项目中尝试时,问题可能更有意义.

设置宽度和高度约束并将IBOutlet设置为它听起来是一个很好的选择,但遗憾的是细胞没有固定的大小,图像需要缩小并与细胞一起生长.删除自动布局也不是一种选择.

Kev*_*ers 1

最后,我在图像视图(到超级视图)上添加了顶部、右侧、底部和左侧间距约束,向其中添加了 IBOutlet 并使用了如下内容:

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;
Run Code Online (Sandbox Code Playgroud)