2016-12-24 96 views
0

我必須爲標籤和ImageView添加tapGesture。如何爲標籤和ImageView創建通用的輕擊手勢方法?如何使用swift編寫UITapGestureRecognizer的通用方法

//TapGestureHandler 
extension EditViewController : UIGestureRecognizerDelegate 
{ 
//Add Gesture on ImageView 
func addGesture() 
{ 
    //Gesture Male 
    let maleTapGesture = UITapGestureRecognizer(target: self, action: #selector(maleGestureTap)) 
    maleTapGesture.delegate = self 
    imgViewMale.addGestureRecognizer(maleTapGesture) 

    //GestureFemale 
    let FemaleTapGesture = UITapGestureRecognizer(target: self, action: #selector(femaleGestureTap)) 
    FemaleTapGesture.delegate = self 
    imgViewFemale.addGestureRecognizer(FemaleTapGesture) 

    //Gesture MaleFemale 
    let maleFeTapGesture = UITapGestureRecognizer(target: self, action: #selector(maleFeGestureTap)) 
    maleFeTapGesture.delegate = self 
    imgViewMaleFe.addGestureRecognizer(maleFeTapGesture) 
} 

//Tap Gesture Male 
func maleGestureTap() 
{ 
    imgViewMale.backgroundColor = hexStringToUIColor(hex: "#CBFFE2") 
} 

//Tap Gesture Female 
func femaleGestureTap() 
{ 
    imgViewFemale.backgroundColor = hexStringToUIColor(hex: "#CBFFE2") 
} 

//Tap Gesture MaleFemale 
func maleFeGestureTap() 
{ 
    imgViewMaleFe.backgroundColor = hexStringToUIColor(hex: "#CBFFE2") 
} 
} 

我不知道我們該怎麼寫一個通用的方法。

+0

你們爲什麼不創建它爲UIView? UILabel和UIImageView擴展UIView –

+0

如何爲UIView創建? 謝謝 – kishor0011

+0

請檢查我更新的問題。 – kishor0011

回答

1

你可以做這樣的事情:

假設你有你需要附加一個自來水處理幾個對象,假設他們都符合UIView的協議:

let subviews: [Any] = [label1, label2, label3, view1, imageview1]() 
label1.tag = 1 //** add a tag to your object ** 
for v in subviews { 
    self.addTapGesture(to: v) 
} 

func tapped(_ sender: UITapGestureRecognizer) { 
    print("tapped") 
    if sender.view?.tag == 1 { 
     // *** this is your label1 view *** 
    } 
} 

func addTapGesture(to: Any?) { 
    if let v = to as? UIView { 
     let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.tapped(_:))) 
     v.addGestureRecognizer(tapGesture) 
     v.isUserInteractionEnabled = true 
    } 
} 
+0

感謝您的回覆。 我會理解並嘗試。 如果可以根據我的代碼編輯它會更好。 謝謝 – kishor0011

+0

如何獲取該信息哪些對象將在tap方法中調用。謝謝 – kishor0011

+0

一個簡單的方法就是給你的視圖添加一個標籤,看看我的編輯 – Shachar

1

與參數定義你的目標selector(tapGestureHandler:)作爲

let tap = UITapGestureRecognizer(target: self, action: Selector("tapGestureHandler:")) 

並檢查您的組件這樣。

func tapGestureHandler(_ sender: UITapGestureRecognizer) { 

    if sender.view is UIView { 
    // sender is a UIView 
    } 
    else if sender.view is UIImageView{ 
    // sender is UIimageView 
    } 
    else{ 
    // sender is none 
    } 
} 

並確保user interaction is true

+0

這是在目標-C ,我只知道迅速。 謝謝 – kishor0011

+0

@ kishor0011重新檢查我的更新回答 –

+0

請檢查我更新的問題。 – kishor0011

相關問題