通过点击任意位置关闭侧边菜单
Dismissing side menu by tapping anywhere
我使用容器视图创建了侧边菜单。每次我按下菜单时,它都会在主视图中滑动。
你可以在这里找到我的项目:
https://github.com/marybnq/side-menu
我需要通过点击 mainVC 中的任意位置来关闭它。
我该怎么做?
简单:
1. mainVC视图增加点击手势,默认关闭
2. 在显示侧边菜单时启用点击手势,以处理点击
3. 隐藏侧边菜单禁用点击手势
试试这个:
class FirstViewController: UIViewController {
@IBOutlet weak var menuConstraint: NSLayoutConstraint!
var sideMenuOpen = false
var gesture : UITapGestureRecognizer?
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self,
selector: #selector(toggleSideMenu), name: NSNotification.Name("ToggleSideMenu"), object: nil)
gesture = UITapGestureRecognizer(target: self, action: #selector(FirstViewController.toggleSideMenu))
}
@objc func toggleSideMenu() {
if sideMenuOpen {
sideMenuOpen = false
menuConstraint.constant = -240
self.view.removeGestureRecognizer(gesture!)
} else {
sideMenuOpen = true
menuConstraint.constant = 0
self.view.addGestureRecognizer(gesture!)
}
}
}
我使用容器视图创建了侧边菜单。每次我按下菜单时,它都会在主视图中滑动。 你可以在这里找到我的项目: https://github.com/marybnq/side-menu
我需要通过点击 mainVC 中的任意位置来关闭它。 我该怎么做?
简单:
1. mainVC视图增加点击手势,默认关闭
2. 在显示侧边菜单时启用点击手势,以处理点击
3. 隐藏侧边菜单禁用点击手势
试试这个:
class FirstViewController: UIViewController {
@IBOutlet weak var menuConstraint: NSLayoutConstraint!
var sideMenuOpen = false
var gesture : UITapGestureRecognizer?
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self,
selector: #selector(toggleSideMenu), name: NSNotification.Name("ToggleSideMenu"), object: nil)
gesture = UITapGestureRecognizer(target: self, action: #selector(FirstViewController.toggleSideMenu))
}
@objc func toggleSideMenu() {
if sideMenuOpen {
sideMenuOpen = false
menuConstraint.constant = -240
self.view.removeGestureRecognizer(gesture!)
} else {
sideMenuOpen = true
menuConstraint.constant = 0
self.view.addGestureRecognizer(gesture!)
}
}
}