我的问题是关于轻按手势。这不起作用

时间:2018-11-20 08:06:24

标签: ios swift

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并运行该代码。添加了该视图但手势不起作用。

1 个答案:

答案 0 :(得分:-1)

正确的方法应该是使用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")
    }

}