gpt4 book ai didi

ios - 自动布局 : can't get the frame size of UICollectionViewCell subViews

转载 作者:可可西里 更新时间:2023-11-01 04:52:51 24 4
gpt4 key购买 nike

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

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

在我的 View Controller 中:

- (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 找到完整的示例项目.

所以问题是这样的:我需要知道 ImageView 的大小,因为我需要请求服务器生成正确大小的图像。 ImageView 的大小为 {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 语句。但是,一旦开始滚动,就会为错误的单元格显示错误的标签。我不明白这是怎么回事。

当您在 example project 中尝试时,这个问题可能更有意义.

设置宽度和高度约束并使其成为 IBOutlets 听起来是个不错的选择,但遗憾的是,单元格没有固定大小,图像需要随着单元格一起收缩和增长。删除自动布局也不是一个选项。

最佳答案

最后,我在 ImageView (到 super View )上添加了顶部、右侧、底部和左侧间距约束,向它们添加了 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;

关于ios - 自动布局 : can't get the frame size of UICollectionViewCell subViews,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17971337/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com