如何防止意外触摸触发 swift 4.2 中的 touchesBegan?
Posted
技术标签:
【中文标题】如何防止意外触摸触发 swift 4.2 中的 touchesBegan?【英文标题】:How to prevent that an accidental touch triggering the touchesBegan in swift 4.2? 【发布时间】:2019-06-15 01:56:33 【问题描述】:我有一个使用 touchesBegan 为用户执行操作的应用程序。但是,有时触摸屏幕只是留下一个文本字段。
有没有办法将 touchesBeagan 设置为仅在 2 或 3 秒后启动,同时保持触摸,如果触摸小于此值,则触发 resignFirstResponder,而不是触发动作?
为了帮助理解这里是我的触摸方法:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?)
Feedback.share.hapticFeedback()
startPoint = nil
guard let touch = touches.first else return
startPoint = touch.location(in: imageView)
//Initialize whatever you need to begin showing selected rectangle below.
rectShapeLayer.path = nil
imageView.layer.addSublayer(rectShapeLayer)
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?)
guard let touch = touches.first, let startPoint = startPoint else return
let currentPoint: CGPoint
if let predicted = event?.predictedTouches(for: touch), let lastPoint = predicted.last
currentPoint = lastPoint.location(in: imageView)
else
currentPoint = touch.location(in: imageView)
let frame = rect(from: startPoint, to: currentPoint)
//Show bounding box
rectShapeLayer.path = UIBezierPath(rect: frame).cgPath
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?)
guard let touch = touches.first, let startPoint = startPoint else return
let currentPoint = touch.location(in: imageView)
let frame = rect(from: startPoint, to: currentPoint)
//Remove bounding box but take snapshot of selected `CGRect` by frame
rectShapeLayer.removeFromSuperlayer()
let memeImage = imageView.snapshot(rect: frame, afterScreenUpdates: true)
save(imageView: imageView, image: memeImage)
【问题讨论】:
【参考方案1】:我找到了一种方法来保证屏幕上的触摸它只是执行 resignFirstResponder 而不是其他功能。
我只更改了 touchesEnded(_:) 方法,添加了“if frame.size.width
这对我来说效果很好。
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?)
guard let touch = touches.first, let startPoint = startPoint else return
let currentPoint = touch.location(in: ivPhoto)
let frame = rect(from: startPoint, to: currentPoint)
rectShapeLayer.removeFromSuperlayer()
if frame.size.width < 1
tfTop.resignFirstResponder()
tfBottom.resignFirstResponder()
else
let memeImage = ivPhoto.snapshot(rect: frame, afterScreenUpdates: true)
saveCrop(cropImage: memeImage)
【讨论】:
以上是关于如何防止意外触摸触发 swift 4.2 中的 touchesBegan?的主要内容,如果未能解决你的问题,请参考以下文章
如何从 Swift 中的 valueChanged 事件中获取触摸坐标
如何在 Touch Down 实现时防止 SwiftUI 上的重新触发
Firebase Deeplink 不触发应用程序:continueUserActivity:restorationHandler,Swift 4.2 Xcode10。