首页 > 解决方案 > 我的问题是关于点击手势。那不起作用

问题描述

class menuView
{
let View = UIView()
let resignView = UIView()
let tap = UITapGestureRecognizer()

    func makeView(view:UIView){
        makeResignView(view: view)
        view.addSubview(View)
        View.translatesAutoresizingMaskIntoConstraints = false
        View.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
        View.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
        View.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
        View.widthAnchor.constraint(equalToConstant: view.frame.width - 100).isActive = true
        View.backgroundColor = UIColor.cyan

    }
    func makeResignView(view:UIView){
         print("resing view is activate")
         resignView.frame = view.frame
         view.addSubview(resignView)
         resignView.backgroundColor = UIColor.blue
         resignView.isUserInteractionEnabled = true
         let tap = UITapGestureRecognizer(target: self, action: #selector(handleDismiss(recog:)))
         resignView.addGestureRecognizer(tap)
   }
    @objc func handleDismiss(recog:UITapGestureRecognizer){
        print("rsing view is dismiss")
        View.removeFromSuperview()
     }
}

class ViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()
    view.backgroundColor = UIColor.gray
}
@IBAction func PlaceView(_ sender: Any) {
    let NewView = menuView()
    NewView.resignView.frame = view.frame
    NewView.makeResignView(view: self.view)
    NewView.makeView(view: self.view)

}

}

在 menuView 类中,我创建一个视图并向其添加手势。在 viewController 类中,我添加 menuView 并运行代码。添加了视图,但手势不起作用。

标签: iosswift

解决方案


正确的方法应该是用 UIView 类继承子视图。

见下面的例子 -

override func viewDidLoad() {
    super.viewDidLoad()
    let newView = subView()
    newView.addGuesture()
    self.view.addSubview(newView)
    // Do any additional setup after loading the view, typically from a nib.
}
class subView:UIView{
    func addGuesture(){
        let tap = UITapGestureRecognizer()
        tap.addTarget(self,action:#selector(handleTap))
        self.isUserInteractionEnabled = true
        self.addGestureRecognizer(tap)
        self.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
        self.backgroundColor = UIColor.red;
    }
    @objc func handleTap(){
        print("tap is working")
    }

}

推荐阅读