Я хочу прокрутить до определенного элемента UICollectionView
внутри viewWillAppear
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[collectionView_ scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:selectedIndex_ inSection:0]
atScrollPosition:UICollectionViewScrollPositionLeft
animated:NO];
}
В iOS 6 этот код сбрасывает приложение, возвращающее
*** Assertion failure in -[UICollectionViewData layoutAttributesForItemAtIndexPath:], /SourceCache/UIKit_Sim/UIKit-2372/UICollectionViewData.m:485
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'must return a UICollectionViewLayoutAttributes instance from -layoutAttributesForItemAtIndexPath: for path <NSIndexPath 0x13894e70> 2 indexes [0, 2]'
На iOS7 он не сработает, а просто ничего не делает.
Прокрутка к правильному элементу работает только в viewDidAppear
, но я хочу показать экран с коллекцией в соответствующем элементе. Я попытался прокрутить его в viewDidLayoutSubviews
, но он также сработает. Обертка вызова внутри try-catch
позволяет избежать сбоя, но он все еще не работает.
В чем смысл этого? Невозможно отобразить правильный элемент?
Большое вам спасибо.
РЕДАКТИРОВАТЬ 1
Я напечатал это на viewWillAppear
и viewDidLayoutSubviews
(selectedIndex_
равно 2, а коллекция имеет 10 элементов):
UICollectionViewLayoutAttributes *test = [collectionView_ layoutAttributesForItemAtIndexPath:[NSIndexPath indexPathForRow:selectedIndex_ inSection:0]];
Результат получается в обоих местах.
<UICollectionViewLayoutAttributes: 0x11b9ff20> index path: (<NSIndexPath: 0x11b9c450> {length = 2, path = 0 - 2}); frame = (0 0; 0 0);
РЕДАКТИРОВАТЬ 2
Это трассировка, которую я печатаю contentSize
коллекции
2013-12-09 08:56:59.300 - didLoad {0, 0}
2013-12-09 08:56:59.315 - willAppear {0, 0}
2013-12-09 08:56:59.350 - viewDidLayoutSubviews {0, 0}
2013-12-09 08:56:59.781 - viewDidLayoutSubviews {3200, 223}
2013-12-09 08:56:59.879 - didAppear {3200, 223}
2013-12-09 08:56:59.882 - viewDidLayoutSubviews {3200, 223}
Вид коллекции создается программно в viewDidLoad
UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
[layout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
collectionView_ = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
[collectionView_ setTranslatesAutoresizingMaskIntoConstraints:NO];
[collectionView_ setDelegate:self];
[collectionView_ setDataSource:self];
[collectionView_ setShowsHorizontalScrollIndicator:NO];
[collectionView_ setPagingEnabled:YES];
[collectionView_ setBackgroundColor:[UIColor whiteColor]];
[collectionView_ registerClass:[MyCollectionViewCell class] forCellWithReuseIdentifier:[MyCollectionViewCell collectionCellIdentifier]];
[scrollView_ addSubview:collectionView_];
scrollView_
создается с помощью XIB (единственного элемента управления в XIB. Мне нужен еще один свиток, чтобы поместить некоторый другой элемент управления под горизонтальную коллекцию). Ограничения этого метода устанавливаются в updateViewConstraints
- (void)updateViewConstraints {
[super updateViewConstraints];
NSDictionary *views = [self viewsDictionary];
NSDictionary *metrics = @{ @"bigMargin" : @12, @"collectionViewHeight" : @(collectionViewHeight_) };
NSMutableString *verticalConstraints = [NSMutableString stringWithString:@"V:|[collectionView_(==collectionViewHeight)]"];
[scrollView_ addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[collectionView_(==scrollView_)]|"
options:0
metrics:nil
views:views]];
if (extendedInformationView_) {
[scrollView_ addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[extendedInformationView_(==scrollView_)]|"
options:0
metrics:nil
views:views]];
[verticalConstraints appendFormat:@"-bigMargin-[extendedInformationView_]"];
}
if (actionListView_) {
[scrollView_ addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[actionListView_(==scrollView_)]|"
options:0
metrics:nil
views:views]];
[verticalConstraints appendFormat:@"-bigMargin-[actionListView_]"];
}
[verticalConstraints appendString:@"-bigMargin-|"];
[scrollView_ addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:verticalConstraints
options:0
metrics:metrics
views:views]];
}
MyCollectionViewCell
создает все свои элементы управления в своем методе initWithFrame
, и вот метод для возврата ячейки.
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
MyCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:[MyCollectionViewCell collectionCellIdentifier]
forIndexPath:indexPath];
// Data filling
return cell;
}