首页 > 解决方案 > UITapGestureRecognizer 不适用于自定义视图类

问题描述

UITapGestureRecognizer在代码 1中工作得很好。tapAction按预期调用。但是它在代码 2中不起作用。有人可以告诉我代码 2有什么问题吗?

thisthis是非常相似的问题,但仍然无法弄清楚)

代码 1:

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let myView : UIView = UIView(frame: CGRect(x: 100, y: 100, width: 100, height: 100))
        myView.backgroundColor = .red
        myView.addGestureRecognizer( UITapGestureRecognizer(target:self,action:#selector(self.tapAction)) )

        self.view.addSubview(myView)
    }

    @objc func tapAction() {
        print("tapped")
    }
}

代码 2:

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let myView = MyView(frame: CGRect(x: 100, y: 100, width: 100, height: 100))
        self.view.addSubview(myView)
    }
}

class MyView : UIView {
    override init(frame: CGRect) {
        super.init(frame: frame)
        initView()
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func initView(){
        let myView : UIView = UIView(frame: CGRect(x: 100, y: 100, width: 100, height: 100))
        myView.backgroundColor = .red
        myView.addGestureRecognizer(UITapGestureRecognizer(target:self,action:#selector(self.doSomethingOnTap)))
        addSubview(myView)
    }

    @objc func doSomethingOnTap() {
        print("tapped")
    }
}

标签: iosswiftuitapgesturerecognizer

解决方案


您正在创建一个在这种特殊情况下超出父边界的子视图,因为视图主视图具有 100 高度和 100 宽度,并且子视图放置在 x: 100 和 y: 100 处,从而定位在确切的末尾的父母。

您在其中创建的子视图initView应该有(x: 0, y: 0)来源。


推荐阅读