【问题标题】:Determine tapped element within UICollectionViewCell确定 UICollectionViewCell 中的点击元素
【发布时间】:2014-05-24 08:14:20
【问题描述】:

我有一个带有自定义单元格的UICollectionView。当我点击一个单元格时,我得到一个collectionView: didSelectItemAtIndexPath:

这不允许我确定单元格内的哪个元素被点击(图像或标签)。如何确定单元格中的哪个元素被点击了?

【问题讨论】:

    标签: ios objective-c ios7 uikit


    【解决方案1】:

    您必须继承 UICollectionViewCell 并在您的 UICollectioView 中包含此类对象。然后你在单元格中创建一个delegate,使用类似

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

    并将您的视图控制器设置为每个单元格的委托。所以你会在这些方法中得到动作而不是collectionView: didSelectItemAtIndexPath:

    【讨论】:

    • 我没有看到 UICollectionViewCell 有委托。我检查了苹果的 IOS 参考,我没有看到任何这样的委托方法:(void)collectionCell:(UICollectionViewCell *)cell didTapButtonWithIndex:(NSUInteger)index
    • 它不存在,你必须创建这个协议
    【解决方案2】:

    您可以将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");
        }
    }
    

    请检查是否在单元格和单个子视图(如标签和图像视图)上设置了用户交互。希望这会有所帮助。

    【讨论】:

      【解决方案3】:

      cellForItem中创建单元格时,只需将UITapGestureRecognizer添加到单元格元素中,并添加目标和选择器即可调用。然后选择器方法将获得一个具有UIView 属性的识别器,该属性将是您选择的元素。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-04-11
        • 1970-01-01
        • 2015-11-18
        • 1970-01-01
        • 2022-01-14
        • 1970-01-01
        • 2018-01-21
        • 1970-01-01
        相关资源
        最近更新 更多