简体   繁体   English

确定UICollectionViewCell中的tapped元素

[英]Determine tapped element within UICollectionViewCell

I have an UICollectionView with custom cells. 我有一个带自定义单元格的UICollectionView When I tap a cell I get a collectionView: didSelectItemAtIndexPath: . 当我点击一个单元格时,我得到一个collectionView: didSelectItemAtIndexPath: .

This doesn't allow me to determine which element inside the cell was tapped (image or label). 这不允许我确定单元格内的哪个元素被轻敲(图像或标签)。 How to determine which element within the cell was tapped? 如何确定单元格中的哪个元素被点击?

You have to subclass UICollectionViewCell and have these kind of objects in your UICollectioView . 你必须继承UICollectionViewCell ,并让这些类型的对象在你的UICollectioView Then you create a delegate in the cells with methods like 然后使用类似方法在单元格中创建delegate

- (void)collectionCell:(UICollectionViewCell *)cell didTapButtonWithIndex:(NSUInteger)index

and set your view controller as delegate for each of this cell. 并将您的视图控制器设置为每个单元格的委托。 So you would get the action in these methods instead of collectionView: didSelectItemAtIndexPath: 因此,您将在这些方法中获取操作而不是collectionView: didSelectItemAtIndexPath:

You can set a tap UITapGestureRecognizer to the entire cell and use - (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event; 您可以将UITapGestureRecognizer设置为整个单元格并使用- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event; to get the tapped object 获取被攻击的对象

In -(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath do this -(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath执行此操作

 UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(cellTapped:)];
    tapGesture.numberOfTapsRequired = 1;
    [cell addGestureRecognizer:tapGesture];

And in cellTapped 并在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");
    }
}

Please do check to see whether the user interaction is set on the cell and individual subviews like labels and imageview's . 请检查是否在单元格和单个子视图(如标签和图像视图)上设置了用户交互。 Hope this helps. 希望这可以帮助。

Just add UITapGestureRecognizer to the cell element when creating the cell in cellForItem and add target and selector to call. 只需添加UITapGestureRecognizer创建的小区时向电池元件cellForItem并添加目标并选择调用。 The selector method will then get a recognizer which has a UIView property, and this property will be your selected element. 然后,选择器方法将获得具有UIView属性的识别器,并且此属性将是您选择的元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM