LoginSignup
0
0

More than 1 year has passed since last update.

TouchesMovedで動かせるUIViewを作ろう

Posted at

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)
    }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0