Skip to content

Instantly share code, notes, and snippets.

@saoudrizwan
Last active October 29, 2023 14:16
Show Gist options
  • Save saoudrizwan/43ba7adad04ae28bbf8bd96431f7749b to your computer and use it in GitHub Desktop.
Save saoudrizwan/43ba7adad04ae28bbf8bd96431f7749b to your computer and use it in GitHub Desktop.
Using a long press gesture recognizer, you can recreate a 'touch up inside' button effect on any view.
let longPress = UILongPressGestureRecognizer(target: self, action: #selector(upgradeAlertViewOtherUpgradesLongPressHandler))
longPress.minimumPressDuration = 0
var longPressGRStartPoint: CGPoint?
var didCancelLongPressGR = false
func viewTouched(sender: UILongPressGestureRecognizer) {
let currentPoint = sender.location(in: self.view)
switch sender.state {
case .began:
print("touch began")
longPressGRStartPoint = sender.location(in: self.view)
didCancelLongPressGR = false
highlightView()
case .changed:
if didCancelLongPressGR { return }
guard longPressGRStartPoint != nil else { return }
//print("touches changed")
let distance = hypotf(Float(currentPoint.x - longPressGRStartPoint!.x), Float(currentPoint.y - longPressGRStartPoint!.y))
//print(distance)
if distance > 55 {
didCancelLongPressGR = true
unhighlightView(shouldTakeAction: false)
}
case .ended:
if didCancelLongPressGR { return }
print("touches ended")
unhighlightView(shouldTakeAction: true)
default:
break
}
}
func highlightView() {
// update ui
print("view highlighted")
}
func unhighlightView(shouldTakeAction: Bool) {
// update ui
print("view unhighlighted")
if !shouldTakeAction { return }
// do the action
print("view action taken")
}
@sk-chanch
Copy link

sk-chanch commented Mar 31, 2021

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment