【问题标题】:Identify Subview in UIView by Location (CGPoint)按位置识别 UIView 中的子视图(CGPoint)
【发布时间】:2019-08-01 00:31:00
【问题描述】:

我正在尝试找出在UIView 中的给定CGPoint 处找到确切子视图(如果有)的最佳方法。

我的场景/ViewController 的一部分是一个自定义的UIView 子类(在 XIB 中设计),它提供了一个 UIStackView 的子视图(也是自定义的,XIB 设计的)。

VC 在那个自定义视图上有一个UITapGestureRecognizer,在我的@IBAction 中,我想确定它的哪个特定子视图被点击,然后相应地处理它:

@IBAction func handleTap(recognizer:UITapGestureRecognizer) {

    let tapLocation = recognizer.location(in: recognizer.view)
    if let subviewTapped = customView.subviewAtLocation(tapLocation) {
        handleTapForSubview(subviewTapped)
    }
}

但是,我不知道如何实现 subviewAtLocation(CGPoint) 方法。我在标准 UIView 方法中找不到任何东西。

欢迎任何关于如何完成的建议。

或者,我考虑为每个子视图添加一个点击识别器,然后委托给父视图,然后委托给 VC,但这感觉效率低下,并且就像它在视图中而不是 VC 中放置了太多控制逻辑.

谢谢。

【问题讨论】:

    标签: ios swift uiview uigesturerecognizer uitapgesturerecognizer


    【解决方案1】:

    解决方案是使用CGRectcontains(point:) 方法。这个想法是迭代堆栈视图的子视图并检查哪些子视图包含触摸点。这里:

    @IBAction func handleTap(recognizer:UITapGestureRecognizer) {
        let tapLocation = recognizer.location(in: recognizer.view)
        let filteredSubviews = stackView.subviews.filter { subView -> Bool in
          return subView.frame.contains(tapLocation)
        }
    
        guard let subviewTapped = filteredSubviews.first else {
          // No subview touched
          return
        }
    
        // process subviewTapped however you want
    }
    

    【讨论】:

    • 效果很好,谢谢!只是为了更加精确,我在您的过滤中添加了第二个检查,其中仅包括该自定义类的子视图:let filteredSubViews = stackView.subviews.filter { subView -> Bool in return subView.frame.contains(location) && subView as? CustomViewClass != nil }
    【解决方案2】:

    //使用 hitTest() 方法。这给出了包含点的视图

    let subView = parentView.hitTest(point, with: nil)
    

    【讨论】:

    • 感谢您的建议。这种方法在某些情况下看起来很有意义,但根据我在hitTest (link) 的 Apple 文档中收集的内容,它实际上拉出了 最远 视图,而不是直接 @ 987654324@。因此,对于这种需求,@ajeferson 的 stackView.subviews.filter 方法可能是直接子视图的更简单途径。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多