在UIView中将tapGestureRecognizer添加到UIImageView并按协议调用方法

时间:2017-02-17 08:01:30

标签: ios swift uiview uiimageview

我想在UIView(蓝色)中的UIImageView(橙色)上识别触摸。并且希望在委托方法中处理触摸事件,该方法将在其他类中使用。但是,我无法通过以下代码识别触摸。如何实现仅在ImageView(橙色)中识别触摸。

enter image description here

代码:

import UIKit

protocol CustomViewDelegate {
    func imageViewTapped()
}

class CustomView: UIView {

    var delegate: CustomViewDelegate?
    var imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = UIColor.blue
        self.imageView.backgroundColor = UIColor.orange
        let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.tapped))
        imageView.addGestureRecognizer(tapGestureRecognizer)
        self.addSubview(imageView)
    }

    public required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    func tapped() {
        print("tapped method called")
        delegate?.imageViewTapped()

    }
}

class ViewController: UIViewController, CustomViewDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()

        let view = CustomView(frame: CGRect(x: 0, y: 0, width: 300, height: 300))
        view.delegate = self
        self.view.addSubview(view)
    }

    func imageViewTapped() {
        print("come to view controller")
    }

}

3 个答案:

答案 0 :(得分:2)

UIImageView默认userinteraction为false,因此在CustomView init中启用imageView userinteraction。

imageView.isUserInteractionEnabled = true

答案 1 :(得分:0)

将不同的UITapGestureRecognizer添加到不同的视图,并根据您的要求进行处理。或者像这样添加标签和访问

 func tapOneAct(sender: UITapGestureRecognizer){

    if let tag = sender.view?.tag {
        switch tag {
        case 1:
            println("First View Tapped")
        case 2:
            println("Second View Tapped")
        default:
            println("Nothing Tapped")
        }
    }

}

答案 2 :(得分:0)

在UIImageView上启用isUserInteractionEnabled属性,因为它默认为false

let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(CustomView.tapped(_:))) 
imageView.isUserInteractionEnabled = true
imageView.addGestureRecognizer(tapGestureRecognizer)
self.addSubview(imageView)
tapGesture方法

中的

func tapgesture(_ sender: UITapGestureRecognizer){
     if sender.state == .ended {
        let touchLocation: CGPoint = sender.location(in: sender.view?.superview)
        if imageView.frame.contains(touchLocation) {
            print("tapped method called")
            delegate?.imageViewTapped()
        }
    }
}