我有一个汉堡菜单,可以从网站上滑进来。每当我选择一个单元格时,它就会关闭菜单。我想添加一个TapRecognizer,以便当您在外面轻按时也可以将其关闭。 This是我的HomeViewController。
var isPresenting = true
let dimmingView = UIView()
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 1.0
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
guard let toViewController = transitionContext.viewController(forKey: .to),
let fromViewController = transitionContext.viewController(forKey: .from) else { return }
let containerView = transitionContext.containerView
let finalWidth = toViewController.view.bounds.width * 0.8
let finalHeight = toViewController.view.bounds.height
if isPresenting{
//addas the dimming view
dimmingView.backgroundColor = .black
dimmingView.alpha = 0.0
containerView.addSubview(dimmingView)
dimmingView.frame = containerView.bounds
//adds the menu view controller to our container
containerView.addSubview(toViewController.view)
//init frame off the screen
toViewController.view.frame = CGRect(x: -finalWidth, y: 0, width: finalWidth, height: finalHeight)
}
let transform = {
self.dimmingView.alpha = 0.5
toViewController.view.transform = CGAffineTransform(translationX: finalWidth, y: 0)
}
let identity = {
self.dimmingView.alpha = 0.0
fromViewController.view.transform = .identity
}
//animates the transition
let duration = transitionDuration(using: transitionContext)
let isCancelledBySystem = transitionContext.transitionWasCancelled
UIView.animate(withDuration: duration, animations: {
self.isPresenting ? transform() : identity()
}) { (_) in
transitionContext.completeTransition(!isCancelledBySystem)
}
}
在外面轻按即可关闭菜单
答案 0 :(得分:1)
您只需要将UITapGestureRecognizer
添加到父视图
然后点击以使用func location(in: UIView?) -> CGPoint
并检查触摸是否在幻灯片菜单的框架之外。
@IBAction func touchWasDetected(_ sender: UITapGestureRecognizer) {
let touchPoint = sender.location(in: view)
if !slideView.frame.contains(touchPoint) {
dissmiss()
}
}
该方法的连接手势动作
答案 1 :(得分:1)
将轻击手势委托分配给您的视图控制器。在手势方法中,保留代码以关闭菜单。下方的委托仅允许在菜单外部进行触摸时接收手势,而在菜单内部则不能关闭。
@objc private func tapGesture(_ gesture: UIGestureRecognizer) {
self.closeMenu()
}
extension SharePathViewController: UIGestureRecognizerDelegate {
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
let point = touch.location(in: view)
return !menuView.frame.contains(point)
}
}