benhi
benhi

Reputation: 582

Making a UICollectioView scroll when text field is selected

I have a UICollectionView. On the inside of one of its items I have UITextField, the problem is: when the keyboard up the textfield is hidden by the keyboard and the user does not see what he is currently writing...

I try the following code:

-(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];

}

But application crash with this error:

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

Upvotes: 3

Views: 1370

Answers (1)

Pavel Smejkal
Pavel Smejkal

Reputation: 3599

Maybe the cell object is not found in the "superview.superview..." calls? I would use this:

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];
}

Upvotes: 3

Related Questions