2017-10-09 80 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檢查更新的答案,希望這會幫助你 –