UICollectionViewCell中的自动布局无法正常工作

rya*_*hon 51 ios autolayout uicollectionview uicollectionviewcell

我有一个简单的UICollectionView,单元格有一个UITextView.UITextView受限于单元格的边缘,因此它们应保持与单元格大小相同的大小.

我遇到的问题是,由于某种原因,当我通过collectionView指定单元格大小时,这些约束不起作用:layout:sizeForItemAtIndexPath:.

我在故事板中将单元格大小设置为320x50.如果我使用sizeForItemAtIndexPath:返回大小为单元格大小2倍的大小,则尽管我设置了约束,但UITextView仍保持相同的高度.我正在使用Xcode 6 GM.

我的视图控制器代码是:

@implementation TestViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    UICollectionViewCell *c = [self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:0]];

    NSLog(@"%f", c.frame.size.height);

    UITextView *tv = (UITextView *)[c viewWithTag:9];
    NSLog(@"%f", tv.frame.size.height);

}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];

    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewFlowLayout *flowLayout = (UICollectionViewFlowLayout *)collectionView.collectionViewLayout;

    CGSize size = flowLayout.itemSize;

    size.height = size.height * 2;

    return size;
}

@end
Run Code Online (Sandbox Code Playgroud)

viewDidAppear中的那些日志:给我输出:
100.00000
50.00000
如您所见,UITextView高度不随单元格高度而变化.


这是我在UICollectionViewCell中约束的UITextView设置的故事板的屏幕截图:

在此输入图像描述

我知道使用自动布局约束可以很好地使用UITableViewCells和动态调整大小.我不知道为什么它不适用于这种情况.有没有人有任何想法?

rya*_*hon 110

好吧,我只是看了iOS开发者论坛.显然这是在iOS 7设备上运行的iOS 8 SDK的一个错误.解决方法是将以下内容添加到UICollectionViewCell的子类中:

- (void)setBounds:(CGRect)bounds {
    [super setBounds:bounds];
    self.contentView.frame = bounds;
}
Run Code Online (Sandbox Code Playgroud)

  • 此问题上的+1也是iOS 8中的一个问题.我有一个集合视图单元格在iOS 7中工作正常,但在iOS 8中没有.这修复了它. (2认同)

Ham*_*mza 40

等效的Swift代码:

override var bounds: CGRect {
    didSet {
      contentView.frame = bounds
    }
}
Run Code Online (Sandbox Code Playgroud)


its*_*dra 24

如果您不是子类,这是解决方案UICollectionViewCell.只需在你的cellForItemAtIndexPath:后面添加这两行dequeueReusableCellWithReuseIdentifier:

OBJ-C

[[cell contentView] setFrame:[cell bounds]];
[[cell contentView] setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight];
Run Code Online (Sandbox Code Playgroud)

斯威夫特 - 2.0

cell.contentView.frame = cell.bounds
cell.contentView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
Run Code Online (Sandbox Code Playgroud)