5

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

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

在我的视图控制器中:

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

在我的单元格子类中,我使用我的属性的设置器来自定义单元格:

- (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 听起来是一个不错的选择,但遗憾的是单元格没有固定大小,并且图像需要随着单元格缩小和增长。删除自动布局也不是一种选择。

4

1 回答 1

1

最后,我在图像视图(到超级视图)上添加了顶部、右侧、底部和左侧间距约束,向它们添加了 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;
于 2013-08-06T12:03:09.460 回答