UIImageViewを例にすると、UIImageViewを継承したクラスを新しく作って、その中でtouchesMovedを書けばOK
.swift
class TouchImageView: UIImageView {
override init(image: UIImage?) {
super.init(image: image)
self.isUserInteractionEnabled = true
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesMoved(touches, with: event)
next?.touchesMoved(touches, with: event)
let touch = touches.first!
let prevPos = touch.previousLocation(in: self.superview)
let nowPos = touch.location(in: self.superview)
let diff = nowPos! - prevPos!
self.layer.position += diff
}
}
extension CGPoint: AdditiveArithmetic {
public static func - (lhs: CGPoint, rhs: CGPoint) -> CGPoint {
return CGPoint(x: lhs.x - rhs.x, y: lhs.y - rhs.y)
}
public static func + (lhs: CGPoint, rhs: CGPoint) -> CGPoint {
return CGPoint(x: lhs.x + rhs.x, y: lhs.y + rhs.y)
}
func toCGSize() -> CGSize {
return CGSize(width: self.x, height: self.y)
}
}