Skip to content

Instantly share code, notes, and snippets.

@takiguri
Created January 14, 2021 01:35
Show Gist options
  • Save takiguri/e1d48bd8aeb1b8085b56258817411177 to your computer and use it in GitHub Desktop.
Save takiguri/e1d48bd8aeb1b8085b56258817411177 to your computer and use it in GitHub Desktop.
Locates the distance of the center of all subviews from the tap location of a UIControl, and returns the subview with the closest center to tap location.
class SomeControl: UIControl {
private var tapGestureRecognizer: UITapGestureRecognizer!
func setupGestureRecognizer() {
tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(tapped(_:)))
addGestureRecognizer(tapGestureRecognizer)
}
@objc func tapped(_ gestureRecognizer: UITapGestureRecognizer) {
let location = gestureRecognizer.location(in: self)
selectedIndex = closestIndex(toPoint: location)
}
func closestIndex(toPoint point: CGPoint) -> Int {
let distances = stackView.subviews.map { abs(point.x - $0.center.x) }
return Int(distances.firstIndex(of: distances.min()!)!)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment