2017-08-30 77 views
1

在我的故事板中,我有幾個圖像爲「啓用了用戶交互」。 在UIViewController我重寫touchesEnded函數。從touches獲取圖像名稱已結束

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { 
     super.touchesEnded(touches, with: event) 
} 

是否有可能讓我得到在這個函數中點擊的圖像的名稱?我寧願不要@IBOutlet的圖像。

+0

你能解釋爲什麼你不喜歡使用IBOutlet的圖像?視圖是動態還是佈局每次顯示都一樣? – Stephen

+0

@stephen它是一個堆棧視圖中的靜態圖像和動態圖像的混合。 –

+0

檢查此答案:https://stackoverflow.com/a/5192999/1718685您應該能夠確定觸摸下方的視圖。 – Stephen

回答

0

我相當肯定,這是不可能的,就像你想要的一樣。圖像視圖不保留它們加載圖像的文件,僅保留圖像數據本身。但我假設你在IB中設置圖像名稱並試圖在觸摸事件後獲取該名稱,在這種情況下,您可以在元素的恢復ID中設置圖像名稱,並通過觸摸元素的restorationIdentifier屬性檢索名稱。

你可以觸摸的元素是這樣的:

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { 
    if let touch: UITouch = touches.first { 
     let location = touch.location(in: self.view) 
     let touchedView = self.view.hitTest(location, with: event) 

     print(touchedView.restorationIdentifier) 
    } 
} 

注意,如果你想這樣做,這樣,你必須設置圖像文件名稱兩次,並進行更改時更改值的兩倍。你正在嘗試什麼味道不好的設計,所以如果有另一種方式我會去做。

+0

我如何檢索touchesEnded中的恢復ID? –

+0

@DanielÅsberg檢查我的編輯 – kevin

0

如果我的問題得到了解決,您不想使用@IBOutlet,但需要獲取點擊圖片的名稱。因此,您也可以通過tagUIImageView來識別它們,然後可以訪問任何信息。

第一從故事板,分配1或任何int值tag屬性並檢查User Interaction EnabledImageView

有以下線 -

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { 
     if let touch: UITouch = touches.first { 
      let location = touch.location(in: self.view) 
      if let touchedView = self.view.hitTest(location, with: event) as? UIImageView { 
       if touchedView.tag == 1 { 
        debugPrint(touchedView.image) 
       } 
      } 
     } 
    } 

希望它可以幫助更換touchesEnded。

+0

你是什麼意思提到**請不要downvote它**。在答案中不允許提及這種類型的metnion。如果你不確定你的答案,那麼只需添加評論。 –

+0

我會如何在touchesEnded中檢索該標籤? –

+0

@NitinGohel我在這裏是新來的,所以不太瞭解,我會添加提交,但它需要50點聲望。 – Maanu