Skip to content

Instantly share code, notes, and snippets.

@JoshuaSullivan
Created February 18, 2016 16:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JoshuaSullivan/9eca84b8b57bb27094b8 to your computer and use it in GitHub Desktop.
Save JoshuaSullivan/9eca84b8b57bb27094b8 to your computer and use it in GitHub Desktop.
This is a simple control which maps touches within its bounds to a 0.0 - 1.0 range on the horizontal and vertical axes, returned as a CIVector.
class TouchCaptureControl: UIControl {
var value: CIVector = CIVector(x: 0.0, y: 0.0)
@IBInspectable var horizontalMinimumValue: CGFloat = 0.0
@IBInspectable var horizontalMaximumValue: CGFloat = 1.0
@IBInspectable var verticalMinimumValue: CGFloat = 0.0
@IBInspectable var verticalMaximumValue: CGFloat = 1.0
@IBInspectable var flipHorizontalAxis: Bool = false
@IBInspectable var flipVerticalAxis: Bool = false
//MARK: - Value Translation
func setValueForPoint(point: CGPoint) {
var normalizedX = point.x / bounds.width
if flipHorizontalAxis { normalizedX = 1.0 - normalizedX }
var normalizedY = point.y / bounds.height
if flipVerticalAxis { normalizedY = 1.0 - normalizedY }
let mappedX = (horizontalMaximumValue - horizontalMinimumValue) * normalizedX + horizontalMinimumValue
let mappedY = (verticalMaximumValue - verticalMinimumValue) * normalizedY + verticalMinimumValue
let newValue = CIVector(x: mappedX, y: mappedY)
if newValue != value {
value = newValue
sendActionsForControlEvents(.ValueChanged)
}
}
//MARK: - Touches
override func beginTrackingWithTouch(touch: UITouch, withEvent event: UIEvent?) -> Bool {
setValueForPoint(touch.locationInView(self))
return super.beginTrackingWithTouch(touch, withEvent: event)
}
override func continueTrackingWithTouch(touch: UITouch, withEvent event: UIEvent?) -> Bool {
setValueForPoint(touch.locationInView(self))
return super.continueTrackingWithTouch(touch, withEvent: event)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment