我必须为标签和ImageView添加tapGesture。如何为Labels和ImageView创建通用的点击手势方法?
//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 :(得分: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
。
答案 1 :(得分: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
}
}