【问题标题】:didSelectItemAtIndexPath of UICollectionView inside of a UIScrollView is not getting called未调用 UIScrollView 内的 UICollectionView 的 didSelectItemAtIndexPath
【发布时间】:2015-05-05 10:08:33
【问题描述】:

我在 UIscrollview 中实现了不可滚动的 UICollectionViewscrollview的大小为100x100collection view的大小为100x200滚动视图的内容大小为 100x200。

我的问题是,当我触摸一些单元格(100x100 矩形之外的单元格)时,没有调用 didSelectItemAtIndexPath

已启用单元格的用户交互。当我将滚动视图高度增加到等于集合视图的高度时,所有单元格都是可触摸的。 提前致谢。

【问题讨论】:

  • 你设置了uicollectionView的“delegate”吗?你符合你的“视图控制器”吗?
  • 是的。当我触摸 100x100 矩形内的单元格时调用该方法。即滚动视图的可见部分

标签: objective-c iphone uiscrollview uicollectionview


【解决方案1】:

因为 scrollView 在 Cell 上重叠...最好的方法是在 UIScrollView 上添加点击 Gesture 之类的,

UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(gestureAction:)];
[recognizer setNumberOfTapsRequired:1];
self.scrollViu.userInteractionEnabled = YES;
[self.scrollViu addGestureRecognizer:recognizer];

在 cellForItemAtIndexPath 方法中添加上述代码并编写手势动作方法,如

-(void)gestureAction:(UITapGestureRecognizer *) sender
{
    CGPoint touchLocation = [sender locationOfTouch:0 inView:self.YourCollectionViewName];
    NSIndexPath *indexPath = [self.YourCollectionViewName indexPathForRowAtPoint:touchLocation];

    NSLog(@"%d", indexPath.item);
}

在上面的手势(动作)方法中,您可以获得与 didSelectItemAtIndexPath 相同的 indexPath。

【讨论】:

  • 但即使我触摸表格外,它也会返回 indexPath.item 为 0
  • 我不知道您的视图层次结构,因为这条线 CGPoint touchLocation = [sender locationOfTouch:0 inView:self.YourCollectionViewName];应该已经处理好了
【解决方案2】:

我的建议是这样使用一个大小与集合视图相同的容器,即 100x200,并在容器上添加集合视图,然后在滚动视图上添加容器。这应该可以解决这个问题。

因为我遇到了类似的问题,因为在滚动视图的不可见部分进行交互时,我无法滚动集合视图并选择集合视图。

【讨论】:

    【解决方案3】:

    Swift 4.0

    在 viewDidLoad 函数中注册手势

      override func viewDidLoad() {
            super.viewDidLoad()
            let tapGesture = UITapGestureRecognizer(target: self, action: #selector(didTapView(gesture:)))
            view.addGestureRecognizer(tapGesture)
        }
    
    @objc func didTapView(gesture: UITapGestureRecognizer) {
        view.endEditing(true)
        let touchLocation:CGPoint = gesture.location(ofTouch: 0, in: self.collectionView)
        let indexPath = self.collectionView.indexPathForItem(at: touchLocation)
        if indexPath != nil {
            let cell = self.collectionView.cellForItem(at: indexPath!)
            if (cell?.isSelected)! {
                //PREFORM DESELECT
            } else {
                //PREFORM SELECT HERE
            }
        }
    } 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多