2016-04-21 74 views
0

我想從我的UIViewController擴展方法在我的UIImageView上添加手勢識別器。如何使用類方法添加手勢識別器作爲選擇器?

我想火當圖像被竊聽的方法是在我迅速擴展聲明一個類的方法:

class func openPopViewWithText(text: String!) { 
    print("fire!") 
} 

我從我的擴展類也增加了選擇。這是我補充的選擇:

infoImageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(UIViewController.openPopViewWithText(_:)))) 

這是當我挖掘的ImageView我得到的錯誤:

[XXXDisplayStatsViewController openPopViewWithText:]: unrecognized selector sent to instance 0x7fd31520ada0 

完整代碼在我的擴展類:

public extension UIViewController { 


func addInfoImageViewWithText(infoText: String){ 
    let margins : CGFloat = 30.0 
    let infoImageView : UIImageView = UIImageView(image: UIImage(named: "info")); 
    let yOrigin : CGFloat = ((self.view.y + self.view.height) - infoImageView.height) - margins 
    infoImageView.frame = CGRectMake(margins, yOrigin, infoImageView.width + 5, infoImageView.height + 5) 
    self.view.insertSubview(infoImageView, atIndex: 0) 
    self.view.bringSubviewToFront(infoImageView) 
    infoImageView.userInteractionEnabled = true 
    infoImageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(UIViewController.openPopViewWithText(_:)))) 
} 

class func openPopViewWithText(text: String!) { 
    print("fire!") 
} 
} 

回答

1

問題是openPopViewWithText函數中的第一個參數是String而不是UITapGestureRecognizer。當你點擊UIImageView手勢識別器被觸發,它將手勢識別器實例傳遞給選擇器,以便可以跟蹤其屬性。所以,你應該做的是改變當前函數簽名這樣的:

class func openPopViewWithText(recognizer: UITapGestureRecognizer) { 
    print("fire!") 
} 

其他,你不應該使用類函數,因爲你不能夠訪問任何UIViewController屬性。

+0

我明白了第一個問題。對於第二個問題,我不想訪問我的任何UIViewController屬性。我只是想創建一個通用的方法爲所有我的UIViewControllers顯示一個popViewController當圖像被挖掘 – AnthonyR

+0

因此,你很好去那麼,只是交換'字符串'類型'UITapGestureRecognizer' –

+0

'... infoImageView。 userInteractionEnabled =真 infoImageView.addGestureRecognizer(UITapGestureRecognizer(目標:自我,動作:#selector(UIViewController.openPopViewWithText(_ :)))) } 類FUNC openPopViewWithText(識別器: 「火」 UITapGestureRecognizer){ 打印() }' 它沒有解決問題我總是有錯誤,但我認爲它來自於我在addGestureRecognizer方法中設置的目標,我設置了'self',所以viewCon troller試圖找到這個方法'openPopViewControllerWithText'但是因爲這個方法是一個類方法,所以找不到它 – AnthonyR

相關問題