2017-10-09 82 views
-1

我有一个视图,添加了一些UIButton。给定CGPoint的 我怎样才能得到按钮。使hitTest(_:with :)函数返回UIButton

示例代码

let location = tapRecognizer.location(in: view) 
    let tapView = view.hitTest(location, with: nil) 

下面的代码将无法工作,我如何能得到UIButton的形式tapView

if let button = tapView as? UIButton { 
     print("text") 
    } 

帮助表示赞赏

+0

什么是你想怎么办?知道哪个按钮被点击了?通过手势识别器调用另一个按钮的动作? –

+0

@DavidRönnqvist我试图知道哪个按钮被录音,并且有太多的按钮...知道哪个按钮添加一些效果时.touchupinside – jin

+0

是否有一个原因,你不能使用[目标行动](https: //developer.apple.com/library/content/documentation/General/Conceptual/CocoaEncyclopedia/Target-Action/Target-Action.html)呢?您可以拥有多个具有相同“动作”的控件。当他们中的一个触发时,他们将自己成为“发件人”。 –

回答

0

当添加按钮,将视图添加目标按钮并为每个按钮分配不同的标签并根据标签执行操作

为了这个目的,你可以使用手势代表像
例子: -

func addGestureOnContentView() -> Void { 
     let tapGesture = UITapGestureRecognizer(target: self, action: #selector(ExploreViewController.hideTableView)) 
     tapGesture.delegate = self 
     self.view.addGestureRecognizer(tapGesture) 
    } 

现在使用的手势代表,如: -

func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool { 
     if gestureRecognizer is UITapGestureRecognizer { 
      if (touch.view?.isDescendant(of: UIButton))! { 
       return false //Perform your task in this block 
      } 
     } 
     return true 
    } 
+0

tks ...但我没有使用按钮来执行操作..只是想获得子视图为UIbutton – jin

+0

@jin检查更新的答案,希望这会帮助你 –