Swift:如何修改handleInputModeList的if条件使其仅响应touchUpInside事件
如何让
handleInputModeList仅在touchUpInside事件触发时执行? 嘿,我来帮你搞定这个问题!你原来代码里的onlyTouchUpEvent并不是UIEvent自带的属性,所以咱们得换个方式,从事件里提取触摸信息来精准判断是不是touchUpInside的触发场景。
下面是修改后的完整代码:
override func viewDidLoad() { super.viewDidLoad() // Some setup button.addTarget(self, action: #selector(handleInputModeList(from:with:)), for: .allTouchEvents) } override func handleInputModeList(from view: UIView, with event: UIEvent) { // 先获取当前按钮上的触摸对象,再判断触摸状态和位置 guard let touch = event.touches(for: button)?.first, touch.phase == .ended, button.bounds.contains(touch.location(in: button)) else { // 不符合条件就调用父类的默认实现 super.handleInputModeList(from: view, with: event) return } // 这里就是你要在touchUpInside时执行的代码啦 // do something }
为啥这么写?给你拆解下:
event.touches(for: button):专门获取绑定在目标按钮上的触摸事件,避免干扰其他视图的触摸。touch.phase == .ended:这是所有“抬手”类事件的基础,说明触摸已经结束了。button.bounds.contains(touch.location(in: button)):这是区分touchUpInside和touchUpOutside的关键——只有当抬手时手指还在按钮范围内,才是标准的touchUpInside触发条件。
如果你的场景不需要严格区分按钮内外的抬手操作,只是想响应所有抬手事件,也可以简化成这样:
override func handleInputModeList(from view: UIView, with event: UIEvent) { guard let touch = event.allTouches?.first, touch.phase == .ended else { super.handleInputModeList(from: view, with: event) return } // do something }
不过更推荐第一种写法,因为它完全贴合touchUpInside的原生触发逻辑哦。
内容的提问来源于stack exchange,提问作者Pavan Kumar
相关产品推荐
相关产品推荐

