【发布时间】:2014-05-24 08:14:20
【问题描述】:
我有一个带有自定义单元格的UICollectionView。当我点击一个单元格时,我得到一个collectionView: didSelectItemAtIndexPath:。
这不允许我确定单元格内的哪个元素被点击(图像或标签)。如何确定单元格中的哪个元素被点击了?
【问题讨论】:
标签: ios objective-c ios7 uikit
我有一个带有自定义单元格的UICollectionView。当我点击一个单元格时,我得到一个collectionView: didSelectItemAtIndexPath:。
这不允许我确定单元格内的哪个元素被点击(图像或标签)。如何确定单元格中的哪个元素被点击了?
【问题讨论】:
标签: ios objective-c ios7 uikit
您必须继承 UICollectionViewCell 并在您的 UICollectioView 中包含此类对象。然后你在单元格中创建一个delegate,使用类似
- (void)collectionCell:(UICollectionViewCell *)cell didTapButtonWithIndex:(NSUInteger)index
并将您的视图控制器设置为每个单元格的委托。所以你会在这些方法中得到动作而不是collectionView: didSelectItemAtIndexPath:
【讨论】:
(void)collectionCell:(UICollectionViewCell *)cell didTapButtonWithIndex:(NSUInteger)index。
您可以将UITapGestureRecognizer 设置为整个单元格并使用- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event; 来获取被点击的对象
在-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
这样做
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(cellTapped:)];
tapGesture.numberOfTapsRequired = 1;
[cell addGestureRecognizer:tapGesture];
在cellTapped
-(void)cellTapped:(UIGestureRecognizer *)gesture
{
CGPoint tapPoint = [gesture locationInView:gesture.view];
UIView *tappedView = [gesture.view hitTest:tapPoint withEvent:nil];
if ([tappedView isKindOfClass:[UILabel class]]) {
NSLog(@"Found");
}
}
请检查是否在单元格和单个子视图(如标签和图像视图)上设置了用户交互。希望这会有所帮助。
【讨论】:
在cellForItem中创建单元格时,只需将UITapGestureRecognizer添加到单元格元素中,并添加目标和选择器即可调用。然后选择器方法将获得一个具有UIView 属性的识别器,该属性将是您选择的元素。
【讨论】: