Swift 4 - 将UITapGestureRecognizer添加到子视图图像 - 不调用该方法

时间:2017-10-05 10:55:17

标签: ios swift

我有以下UITapGestureRecognizer设置,但该方法未被调用?

注意:UITapGestureRecognizer已添加到子视图项目中。

此外,它在UIGestureRecognizerDelegate本身添加SUStepView时也有效 - 唯一的问题是我需要在容器中使用它。

class StepViewContainer: NSObject, UIGestureRecognizerDelegate {
var view: SUStepView?

    @objc func tapAction(recognizer: UITapGestureRecognizer) {

    }

    override init(){
        super.init()
        // View
        self.view = Bundle.main.loadNibNamed("SignupV3Views", owner: self, options: nil)![0] as? SUStepView

        let mytapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(tapAction))
        mytapGestureRecognizer.numberOfTapsRequired = 1
        self.view?.imageView.addGestureRecognizer(mytapGestureRecognizer)            
    }
}

StepViewContainer中的视图:

class SUStepView: UIView {
@IBOutlet weak var imageView: UIImageView!

    @objc public func nextStepTap(sender: UITapGestureRecognizer) {
    }

    override func awakeFromNib() {
        let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(nextStepTap))
        tapGestureRecognizer.numberOfTapsRequired = 1
        self.imageView.addGestureRecognizer(tapGestureRecognizer)

        self.imageView.isUserInteractionEnabled = true
        self.imageView.layer.masksToBounds = true
        self.imageView.layer.cornerRadius = self.imageView.frame.size.width / 2
        self.imageView.clipsToBounds = true

}

2 个答案:

答案 0 :(得分:21)

Swift 4代码:

TapGesture:

 tapGesture = UITapGestureRecognizer(target: self, action: #selector(ViewController.myviewTapped(_:)))
 tapGesture.numberOfTapsRequired = 1
 tapGesture.numberOfTouchesRequired = 1

ImageView点按:

    self.imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width/2.0, height: self.view.frame.size.height/2.0))
    self.imageView.isUserInteractionEnabled = true
    self.imageView.backgroundColor = UIColor.red
    self.imageView.layer.masksToBounds = true
    self.imageView.layer.cornerRadius = self.imageView.frame.size.width / 2
    self.imageView.clipsToBounds = true
    self.imageView.addGestureRecognizer(tapGesture)
    self.view.addSubview(self.imageView)

拨打电话

@objc func myviewTapped(_ sender: UITapGestureRecognizer) {
    if self.imageView.backgroundColor == UIColor.yellow {
        self.imageView.backgroundColor = UIColor.green
    }else{
        self.imageView.backgroundColor = UIColor.yellow
    }
}

答案 1 :(得分:10)

试试这个。

let mytapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(myTapAction))
mytapGestureRecognizer.numberOfTapsRequired = 1
self.imageView.addGestureRecognizer(mytapGestureRecognizer)

方法

@objc func myTapAction(recognizer: UITapGestureRecognizer) {
}