RIT视图和侧面菜单视图无法识别UITapGestureRecognizer

时间:2019-11-23 01:58:49

标签: ios swift

我有侧边菜单,如果打开的话,我会以编程方式创建UIView来覆盖主视图,然后使用TapGeastureRecognizer单击它,菜单应该关闭,并且一切工作正常。左)版本存在问题:

TapGeastureRecognizer在主视图上无法识别,但在侧面菜单视图上可以识别,如图所示。 SideMenu Opened Image Here.


import UIKit

class ContainerVC: UIViewController {
    @IBOutlet weak var sideMenuConstraint: NSLayoutConstraint!
    @IBOutlet weak var containerView: UIView!
    @IBOutlet weak var sideMenuView: UIView!
    var sideMenuOpen = false
    let cover = UIView()

    override func viewDidLoad() {
        super.viewDidLoad()
        NotificationCenter.default.addObserver(self, selector: #selector(toggleSideMenu(_:)), name: NSNotification.Name("ToggleSideMenu"), object: nil)

    }
    func createCover(){
        self.cover.frame = CGRect(x: self.containerView.frame.origin.x, y: 0, width: self.containerView.frame.width, height: self.containerView.frame.height)
        self.cover.backgroundColor = UIColor(white: -1, alpha: 0.4)
        self.cover.isUserInteractionEnabled = true
        let gesture = UITapGestureRecognizer(target: self, action:  #selector(self.closeMenu(sender:)))
        self.cover.addGestureRecognizer(gesture)
    }
    @objc func toggleSideMenu(_ notification: NSNotification){
        if !sideMenuOpen {
            self.sideMenuOpen = true
            self.sideMenuConstraint.constant = 0
            self.view.addSubview(cover)
        }else{
            self.sideMenuOpen = false
            self.sideMenuConstraint.constant = -240
            cover.removeFromSuperview()
        }

        UIView.animate(withDuration: 0.3, animations: {
            self.view.layoutIfNeeded()
            }, completion: { (finished: Bool) in
                self.createCover()
        })
    }

    @objc func closeMenu(sender: UIView){
        self.sideMenuOpen = false
        self.sideMenuConstraint.constant = -240
        cover.removeFromSuperview()
        UIView.animate(withDuration: 0.3) {
            self.view.layoutIfNeeded()
        }
    }

}

2 个答案:

答案 0 :(得分:0)

cover添加为子视图时,它会添加到所有其他子视图的顶部。 addSubview(_:)上的Apple文档:

  

参数: view

     

要添加的视图。添加后,该视图将显示在所有其他子视图的顶部。

每次添加封面时都需要重新排列视图,例如:

view.sendSubviewToBack(cover)
view.sendSubviewToBack(containerView)

答案 1 :(得分:0)

萨拉姆

我有一个类似的问题,请检查一下

iOS mirrored Arabic in Xcode 7.3