ios UICollectionView 单元格子视图不调整大小

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15303100/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 22:37:54  来源:igfitidea点击:

UICollectionView cell subviews do not resize

iossizecellsubviewuicollectionview

提问by ceekay

In a CollectionView, some cells should have an additional subview or layer. The CollectionViewcan be told to resize it's cells, thus all content needs to resize appropriately.

在 a 中CollectionView,某些单元格应该有一个额外的子视图或层。该CollectionView可以告诉调整其大小的细胞,因此,所有的内容需要适当地调整。

Currently, the cell is initialized from a nib containing a cell with imageview; the cell nib is linked to a custom UICollectionViewCellsubclass, that only does the init. Autoresize subviews is checked.

目前,该单元格是从包含带有 imageview 的单元格的笔尖初始化的;单元笔尖链接到自定义UICollectionViewCell子类,该子类仅执行 init。自动调整子视图被选中。

The CollectionViewis told to resize the cell by a value derived and returned in sizeForItemAtIndexPath:. I have subclassed a FlowLayout but it only specifies ScrollDirectionand Insets.

CollectionView被告知通过导出和返回的值,以调整细胞sizeForItemAtIndexPath:。我已经对 FlowLayout 进行了子类化,但它只指定了ScrollDirectionInsets

All of that is working fine. Problem: How do I add subview/layer to the cell so it also resizes correctly? I tried adding subviews and layers with translatesAutoresizingMaskIntoConstraintsoff, but these do not automatically change size at all. Also tried to use code frame/view instead of nib.

所有这些都运行良好。问题:如何将子视图/图层添加到单元格,以便它也能正确调整大小?我尝试使用translatesAutoresizingMaskIntoConstraints关闭添加子视图和图层,但这些根本不会自动更改大小。还尝试使用代码框架/视图而不是笔尖。

The best I got now is a cell.contentView.layersublayer which I add in cellForItemAtIndexPath:; that is "manually" resized by storing the cell's frame.sizefrom sizeForItemAtIndexPath:, which is not only ugly but also ends up with the sublayer having various sizes for different cells.

我现在得到的最好的是cell.contentView.layer我添加的子层cellForItemAtIndexPath:;这是通过存储单元格的frame.sizefrom来“手动”调整大小的sizeForItemAtIndexPath:,这不仅很丑陋,而且最终导致子层对于不同的单元格具有不同的大小。

Any help appreciated!

任何帮助表示赞赏!

采纳答案by ceekay

The solution was to turn off AutoConstraints for the cell xib and activate the flexible width/height arrows in the AutoResize for the imageviews.

解决方案是关闭单元格 xib 的 AutoConstraints 并激活图像视图的 AutoResize 中的灵活宽度/高度箭头。

回答by Alfie Hanssen

I ran into the same issue just now.

我刚才遇到了同样的问题。

When using the UICollectionViewFlowLayoutDelegate method to set the cell size depending on device and device-orientation, the size would be calculated properly but subviews would not resize to fill the newly size cell. The effect was a large blank cell with small subviews that don't fill the cell's bounds / remain the size equal to their current value in the xib file.

当使用 UICollectionViewFlowLayoutDelegate 方法根据设备和设备方向设置单元格大小时,将正确计算大小,但子视图不会调整大小以填充新大小的单元格。效果是一个大的空白单元格,带有不填充单元格边界的小子视图/保持大小等于它们在 xib 文件中的当前值。

I solved this by doing the following in awakeFromNib:

我通过执行以下操作解决了这个问题awakeFromNib

- (void)awakeFromNib
{
    [super awakeFromNib];

    self.contentView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    self.contentView.translatesAutoresizingMaskIntoConstraints = YES;
}

Prior to doing this, the contentView mask was nil.

在此之前, contentView 掩码是nil.

回答by NSCoyote

*override func awakeFromNib() {
    super.awakeFromNib()

    self.contentView.autoresizingMask.insert(.FlexibleHeight)
    self.contentView.autoresizingMask.insert(.FlexibleWidth)
}

This worked for me.. This code goes inside of your subclassed UICollectionViewCell.swift file (where your code involving the custom cell is located)

这对我有用..此代码位于您的子类 UICollectionViewCell.swift 文件中(您的涉及自定义单元格的代码所在的位置)

Swift solution*

快速解决方案*

回答by Praneeth Wanigasekera

As an alternative to enabling AutoResizingMask, for custom UICollectionViewLayouts that have variable height for example where you are setting some constraints manually and need translatesAutoresizingMaskIntoConstraints to remain NO, you can add the following to layoutSubviews in the cell:

作为启用 AutoResizingMask 的替代方法,对于具有可变高度的自定义 UICollectionViewLayouts,例如您手动设置一些约束并且需要 translatesAutoresizingMaskIntoConstraints 保持 NO,您可以将以下内容添加到单元格中的 layoutSubviews:

self.contentView.frame = self.bounds;

This worked to fix all of my custom collection view layouts that had problens with Xcode 6.

这有助于修复我所有在 Xcode 6 中存在问题的自定义集合视图布局。

回答by ceekay

In another project without xibs i subclassed UICollectionViewCell and did this for the same effect:

在另一个没有 xibs 的项目中,我将 UICollectionViewCell 子类化,并为相同的效果这样做:

#import "CVcell.h"

@implementation CVcell

@synthesize cellImage;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {

        CGFloat cellSize = self.contentView.bounds.size.width;
        cellImage = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, cellSize, cellSize)];
        [cellImage setClipsToBounds:YES];

        cellImage.translatesAutoresizingMaskIntoConstraints = NO;
        cellImage.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
        [self.contentView addSubview:cellImage];

    }
    return self;
}

@end

回答by Pedroinpeace

I always prefer autolayout when possible. But Sometimes usings frames and bounds just is a timesaver when a view is determined straightforward by only its superview.

如果可能,我总是更喜欢自动布局。但有时,当视图仅由其父视图直接确定时,使用框架和边界只是一种节省时间的方法。

In the case of UICollectionViewCell I set an image to be the cells frame + self.imageView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;

在 UICollectionViewCell 的情况下,我将图像设置为单元格框架 + self.imageView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;

But when I had different sizes of cells in the collectionView it messed up things and the image sometimes took the size of a different cell.

但是当我在 collectionView 中有不同大小的单元格时,它会把事情搞砸,图像有时会占用不同单元格的大小。

So I turned to working with the the cells bounds and - ye that acually worked out fine.

所以我转向处理单元格边界 - 你的结果很好。

So maybe give that a try?

所以也许试一试?

回答by jlmendezbonini

A simple auto layout solution is to set constraints to the container view.

一个简单的自动布局解决方案是为容器视图设置约束。

So if we have an image view with a parent view, we basically want to tell the subview (the image view) to maintain a leading, trailing, bottom, and top space distance of 0 to the container view.

所以如果我们有一个带有父视图的图像视图,我们基本上是想告诉子视图(图像视图)与容器视图保持 0 的前导、尾随、底部和顶部空间距离。

Auto layout constraints to resize with parent view

使用父视图调整大小的自动布局约束

回答by Serluca

@Alfie Hanssen solution (here) didn't work properly for me, according with this article:

根据这篇文章,@Alfie Hanssen 解决方案(此处)对我不起作用:

The size of the cell view in the XIB is 50 x 50 points, which is the default size of the collection view cells as set in the flow layout. Even if it's a bit hard to work with a cell this small in Interface Builder, it's better to not change the default size. The problem is that Auto Layout considers the manually set size as being fixed and generates a NSAutoresizingMaskLayoutConstraint error when it tries to adjust the cells height automatically

XIB 中单元格视图的大小为 50 x 50 点,这是流布局中设置的集合视图单元格的默认大小。即使在 Interface Builder 中使用这么小的单元格有点困难,最好不要更改默认大小。问题是自动布局认为手动设置的大小是固定的,并在尝试自动调整单元格高度时生成 NSAutoresizingMaskLayoutConstraint 错误

I have inspected the UICollectionViewCell and I found that there is a view between the cell and the contentView, and that view has intrinsic width and height constraints. Instead of the AutoresizingMask I'm just updating as below and seems working for me.

我检查了 UICollectionViewCell,发现单元格和 contentView 之间有一个视图,并且该视图具有固有的宽度和高度约束。而不是 AutoresizingMask 我只是更新如下,似乎对我有用。

override func layoutSubviews() {
    contentView.superview?.frame = bounds
    super.layoutSubviews()
}

回答by Ethandf

I'm adding subView and constraint programmatically, the following code works for me:

我正在以编程方式添加 subView 和约束,以下代码适用于我:

lazy var imageView: UIImageView = { [unowned self] in
    let imageView = UIImageView(frame: self.contentView.frame)
    imageView.contentMode = .scaleAspectFill
    imageView.clipsToBounds = true

    return imageView
}() 

func updateCellWith(image: UIImage) {

    contentView.subviews.forEach { 
self.autoresizesSubviews = YES;
.removeFromSuperview() } contentView.addSubview(imageView) imageView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 0).isActive = true imageView.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant: 0).isActive = true imageView.rightAnchor.constraint(equalTo: contentView.rightAnchor, constant: 0).isActive = true imageView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: 0).isActive = true self.imageView.autoresizingMask.insert(.flexibleHeight) self.imageView.autoresizingMask.insert(.flexibleWidth) imageView.image = image }

回答by Corona

I had the same problem. Switching between two layouts did not resize the Pictures (UIImage) inside my cells. My Cells where build without a xib. And I used two different cell classes for each CollectionViewCustomLayout.

我有同样的问题。在两个布局之间切换并没有调整我单元格内的图片 (UIImage) 的大小。我的 Cells 在没有 xib 的情况下构建。我为每个 CollectionViewCustomLayout 使用了两个不同的单元格类。

I fixed this programatically with this:

我用这个以编程方式修复了这个:

cell.backgroundView[[UIImageView alloc] initWithImage: SumDummyImage ];

in my UICollectionViewCell subclasses.

在我的 UICollectionViewCell 子类中。

But this only worked for me by adding the Picture as a cells backgroundpicture like this:

但这仅对我有用,将图片添加为像这样的单元格背景图片:

##代码##