选择文本字段时使 UICollectioView 滚动

Making a UICollectioView scroll when text field is selected

我有一个UICollectionView。在其中一个项目的内部,我有 UITextField,问题是:当 textfield 向上的 keyboardkeyboard 隐藏时,用户看不到什么他目前正在写作...

我试试下面的代码:

-(void)textFieldDidBeginEditing:(UITextField *)textField {

    UICollectionViewCell *cell;

    if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_6_1) {
        cell = (UICollectionViewCell *) textField.superview.superview;
    } else {
        cell = (UICollectionViewCell *) textField.superview.superview.superview;
    }

    [self.collectionView scrollToItemAtIndexPath:[self.collectionView indexPathForCell:cell] atScrollPosition:UICollectionViewScrollPositionTop animated:YES];

}

但应用程序崩溃并出现此错误:

2015-05-20 18:40:18.431 MyAPP[1154:111390] -[UICollectionView _layoutAttributes]: unrecognized selector sent to instance 0x1511a200
2015-05-20 18:40:18.432 MyAPP[1154:111390] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UICollectionView _layoutAttributes]: unrecognized selector sent to instance 0x1511a200'
*** First throw call stack:
(0x278b55a7 0x3549bc77 0x278baa6d 0x278b8949 0x277e9b68 0x2af7c3cd 0x122033 0x2aead5bd 0x2ae32279 0x2ae3257b 0x2aeac0b7 0x120b99 0x2afbdb39 0x2afbd843 0x2af37b61 0x2af37b61 0x2adaef67 0x2ade3ddd 0x2ade36ad 0x2adb9fbd 0x2b02dbb5 0x2adb8a07 0x2787c237 0x2787b64b 0x27879cc9 0x277c6b51 0x277c6963 0x2ed051a9 0x2ae18c91 0xa6fff 0x35a44aaf)
libc++abi.dylib: terminating with uncaught exception of type NSException

可能在 "superview.superview..." 调用中找不到单元格对象?我会用这个:

UICollectionViewCell *cell;
UIView *superview = textField.superview;

while (superview) {
    if([superview isKindOfClass:[UICollectionViewCell class]]) {
        cell = (UICollectionViewCell *)superview;
        break;
    }
    superview = superview.superview;
}

if(cell == nil) {
    NSLog(@"Error...");
} else {
    [self.collectionView scrollToItemAtIndexPath:[_collectionView indexPathForCell:cell] atScrollPosition:UICollectionViewScrollPositionTop animated:YES];
}