如何检测导航栏最右侧边缘的触摸事件
如何检测导航栏最右侧边缘的触摸事件
嘿,我来帮你搞定这个问题!你想让导航栏右侧的UIBarButtonItem能响应屏幕最右边缘的触摸,就像苹果Notes应用那样对吧?之前你试了自定义视图加超出父视图的约束,但触摸没生效,其实核心问题是视图的触摸检测范围默认只在自身 bounds 内,超出的部分系统不会识别,下面给你两个实用的解决方案:
方案一:自定义UIButton扩展触摸范围
这是最直接的方法,我们可以自定义一个UIButton,重写它的point(inside:with:)方法,把触摸检测的范围直接延伸到屏幕最边缘。
首先创建自定义按钮类:
class ExtendedTouchButton: UIButton { override func point(inside point: CGPoint, with event: UIEvent?) -> Bool { // 先获取屏幕宽度,计算需要扩展到最右边缘的宽度 guard let window = UIApplication.shared.windows.first else { return super.point(inside: point, with: event) } let screenWidth = window.bounds.width // 转换按钮的frame到窗口坐标系,计算按钮右侧到屏幕最右的距离 let buttonFrameInWindow = superview?.convert(bounds, to: window) ?? bounds let extendWidth = screenWidth - buttonFrameInWindow.maxX // 合并原按钮区域和扩展区域 let extendedBounds = bounds.union(CGRect( x: bounds.maxX, y: bounds.minY, width: extendWidth, height: bounds.height )) return extendedBounds.contains(point) } }
然后把这个按钮作为UIBarButtonItem的customView使用:
// 创建自定义按钮 let actionButton = ExtendedTouchButton(type: .system) actionButton.setImage(UIImage(systemName: "plus"), for: .normal) actionButton.addTarget(self, action: #selector(yourActionMethod), for: .touchUpInside) // 包装成UIBarButtonItem并设置到导航栏 let barButton = UIBarButtonItem(customView: actionButton) navigationItem.rightBarButtonItems = [barButton]
这样设置后,从按钮右侧到屏幕最边缘的区域都会响应触摸,完全复刻Notes的效果。
方案二:给导航栏添加全局触摸手势
如果不想自定义按钮,你可以给导航栏添加一个手势识别器,手动判断触摸点是否在目标区域内:
override func viewDidLoad() { super.viewDidLoad() // 添加触摸手势到导航栏 let navBarTap = UITapGestureRecognizer(target: self, action: #selector(handleNavBarTap(_:))) navigationController?.navigationBar.addGestureRecognizer(navBarTap) } @objc private func handleNavBarTap(_ gesture: UITapGestureRecognizer) { let tapPoint = gesture.location(in: navigationController?.navigationBar) // 获取目标UIBarButtonItem的customView(这里假设是第一个右侧按钮) guard let targetButton = navigationItem.rightBarButtonItems?.first?.customView as? UIButton else { return } let buttonFrame = targetButton.frame // 判断触摸点是否在按钮右侧到导航栏最右的垂直区域内 let isInExtendedArea = tapPoint.x >= buttonFrame.maxX && tapPoint.y >= buttonFrame.minY && tapPoint.y <= buttonFrame.maxY if isInExtendedArea { // 触发按钮的点击事件 targetButton.sendActions(for: .touchUpInside) } }
这个方法的好处是不用修改现有按钮的类,但要注意如果导航栏上有多个按钮,需要额外判断避免误触发其他按钮的事件。
备注:内容来源于stack exchange,提问作者Elijah
相关产品推荐
相关产品推荐

