How to disappear sidemenu without button in swift 4

I have some question. i made side menu in swift4.

when i clicked button, side menu appear and disappear.

but i want make disappear side menu without button.

for example, when i clicked another view (not side menu), disappear sidemenu.

my code like this.

class ContainerVC: UIViewController {

@IBOutlet weak var constaint: NSLayoutConstraint!
var sideMenuOpen = false

override func viewDidLoad() {
    super.viewDidLoad()

    NotificationCenter.default.addObserver(self,  selector: #selector(toggleSideMenu), name: NSNotification.Name("ToggleSideMenu"), object: nil)
}

@objc func toggleSideMenu(){

    if sideMenuOpen {

        sideMenuOpen = false
        constaint.constant = -130

    }else {
        sideMenuOpen = true
        constaint.constant = 0

    }
    UIView.animate(withDuration: 0.3){
        self.view.layoutIfNeeded()
    }
}

enter image description here

when i click white background (view) , disappear side menu. Thanks.

1 answer

  • answered 2018-04-17 06:21 aBilal17

    You can use code something like that, please add following code in viewDidLoad()

    let tap = UITapGestureRecognizer(target: self, action: #selector(dismiss(fromGesture:)))
        self.view.addGestureRecognizer(tap)
    

    Then create a function for dismiss

    @objc func OpenSideMenu(){
        sideMenuOpen = true
        constaint.constant = 0
        UIView.animate(withDuration: 0.3){
            self.view.layoutIfNeeded()
        }
    }
    
    @objc func closeSideMenu(){
        sideMenuOpen = false
        constaint.constant = -130
        UIView.animate(withDuration: 0.3){
            self.view.layoutIfNeeded()
        }
    }
    
    @objc func dismiss(fromGesture gesture: UISwipeGestureRecognizer) {
        closeSideMenu()
    }
    

    Hope this will work.