Created
January 14, 2021 01:35
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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