Skip to content

Instantly share code, notes, and snippets.

@brennanMKE
Created July 31, 2014 01:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brennanMKE/e89bf7a28d96812d6a22 to your computer and use it in GitHub Desktop.
Save brennanMKE/e89bf7a28d96812d6a22 to your computer and use it in GitHub Desktop.
Tappable UITextView in a UICollectionView
@implementation TappableTextView
- (instancetype)init {
self = [super init];
if (self) {
[self setup];
}
return self;
}
- (instancetype)initWithCoder:(NSCoder *)coder {
self = [super initWithCoder:coder];
if (self) {
[self setup];
}
return self;
}
- (instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
[self setup];
}
return self;
}
- (void)setup {
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTapRecognized:)];
singleTap.numberOfTapsRequired = 1;
[self addGestureRecognizer:singleTap];
}
- (void)singleTapRecognized:(id)sender {
UIView *superview = self.superview;
UICollectionViewCell *cell = nil;
NSIndexPath *indexPath = nil;
while (superview) {
if ([superview isKindOfClass:[UICollectionViewCell class]]) {
cell = (UICollectionViewCell *)superview;
}
if ([superview isKindOfClass:[UICollectionView class]] && cell) {
UICollectionView *collectionView = (UICollectionView *)superview;
indexPath = [collectionView indexPathForCell:cell];
NSAssert(collectionView.delegate, @"Delegate must be defined");
NSAssert([collectionView.delegate respondsToSelector:@selector(collectionView:didSelectItemAtIndexPath:)], @"Selection must be supported");
if (indexPath && [collectionView.delegate respondsToSelector:@selector(collectionView:didSelectItemAtIndexPath:)]) {
[collectionView.delegate collectionView:collectionView didSelectItemAtIndexPath:indexPath];
}
return;
}
superview = superview.superview;
}
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment