按位置识别UIView中的子视图(CGPoint)

问题描述 投票:1回答:2

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

我的场景/ 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方法中找到任何东西。

任何关于如何做的建议都会受到欢迎。

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

谢谢。

ios swift uiview uigesturerecognizer uitapgesturerecognizer
2个回答
1
投票

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

@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
}

0
投票

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

let subView = parentView.hitTest(point, with: nil)
© www.soinside.com 2019 - 2024. All rights reserved.