Автоматическое расположение в UICollectionViewCell не работает
У меня есть простой UICollectionView с ячейками, которые имеют один UITextView. UITextView ограничен краями ячейки, поэтому они должны оставаться того же размера, что и размер ячейки.
У меня проблема в том, что по какой-то причине эти ограничения не работают, когда я задаю размер ячейки через collectionView:layout:sizeForItemAtIndexPath:.
У меня размер ячейки установлен на 320x50 в раскадровке. Если я возвращаю размер в 2 раза больше размера ячейки с помощью sizeForItemAtIndexPath:, 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 не меняется с высотой ячейки.
Вот скриншот раскадровки, которую я настроил с помощью UITextView, ограниченного в UICollectionViewCell:
Я знаю, что использование автоматических ограничений макета прекрасно работает с UITableViewCells и динамическим изменением размера. Я понятия не имею, почему это не работает в этом случае. У кого-нибудь есть какие-либо идеи?
4 ответа
Ну, я только что посмотрел на форумах разработчиков iOS. Видимо, это ошибка в iOS 8 SDK, работающем на устройствах iOS 7. Обходной путь должен добавить следующее к вашему подклассу UICollectionViewCell:
- (void)setBounds:(CGRect)bounds {
[super setBounds:bounds];
self.contentView.frame = bounds;
}
Эквивалентный код Swift:
override var bounds: CGRect {
didSet {
contentView.frame = bounds
}
}
Вот решение, если вы не подкласс UICollectionViewCell
, Просто добавьте эти две строки под вашим cellForItemAtIndexPath:
после dequeueReusableCellWithReuseIdentifier:
Obj-C,
[[cell contentView] setFrame:[cell bounds]];
[[cell contentView] setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight];
Свифт - 2.0
cell.contentView.frame = cell.bounds
cell.contentView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
Swift 2.0:
cell.contentView.frame = cell.bounds
cell.contentView.autoresizingMask = [UIViewAutoresizing.FlexibleWidth, UIViewAutoresizing.FlexibleHeight]