我有一个简单的UICollectionView,它的单元格只有一个UITextView。UITextView被约束到单元格的边缘,因此它们应该保持与单元格大小相同的大小。
我遇到的问题是,由于某些原因,当我通过collectionView:layout:sizeForItemAtIndexPath:.指定像元大小时,这些约束不起作用
我在故事板中将单元大小设置为320x50。如果我用sizeForItemAtIndexPath:返回一个高度是单元格高度的2倍的大小,尽管我设置了约束,UITextView仍然保持相同的高度。我使用的是Xcode6 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和动态调整大小。我不知道为什么它在这种情况下不起作用。有谁有什么想法吗?
发布于 2014-09-13 05:38:52
我刚刚在iOS开发者论坛上看了一下。显然,这是一个运行在iOS 7设备上的iOS 8软件开发工具包的错误。解决方法是将以下内容添加到UICollectionViewCell的子类中:
- (void)setBounds:(CGRect)bounds {
[super setBounds:bounds];
self.contentView.frame = bounds;
}
override var bounds: CGRect {
didSet {
contentView.frame = bounds
}
}
发布于 2015-01-21 14:22:37
等效Swift代码:
override var bounds: CGRect {
didSet {
contentView.frame = bounds
}
}
发布于 2014-12-16 08:42:02
这就是解决方案,如果你没有子类化UICollectionViewCell
的话。只需在dequeueReusableCellWithReuseIdentifier:
之后的cellForItemAtIndexPath:
下添加以下两行
Obj-C
[[cell contentView] setFrame:[cell bounds]];
[[cell contentView] setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight];
Swift - 2.0
cell.contentView.frame = cell.bounds
cell.contentView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
https://stackoverflow.com/questions/25804588
复制相似问题