【发布时间】:2014-11-06 09:56:47
【问题描述】:
我有一个简单的 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
viewDidAppear 中的那些日志:给我一个输出:
100.00000
50.00000
如您所见,UITextView 的高度不会随着单元格的高度而变化。
这是我在 UICollectionViewCell 中使用约束的 UITextView 设置的故事板的屏幕截图:
我知道使用自动布局约束适用于 UITableViewCells 和动态调整大小。我不知道为什么它在这种情况下不起作用。有人有什么想法吗?
【问题讨论】:
标签: ios uicollectionview autolayout uicollectionviewcell