LoginSignup
0
1

More than 1 year has passed since last update.

【Swift】タップした時に追従してくるViewを作成する

Posted at

はじめに

このような感じで、タップした位置に追従してくるようなViewを作成したいと思います。
ezgif.com-gif-maker (6).gif

実装

コピペで作成できます。

final class ViewController: UIViewController {

    private var myView: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()

        myView = UIView()
        myView.frame.size = CGSize(width: 100, height: 100)
        myView.center = self.view.center
        myView.backgroundColor = .red
        myView.isUserInteractionEnabled = true
        self.view.addSubview(myView)

    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        if touches.first!.view == self.view {
            let after = touches.first!.location(in: self.view)
            let before = myView.center
            let deltaX = after.x - before.x
            let deltaY = after.y - before.y
            UIView.animate(withDuration: 0.3) {
                self.myView.transform = CGAffineTransform(translationX: deltaX, y: deltaY)
            }
        }
    }

}

解説

touchesBeganはタップした時に呼ばれるメソッドです。(touchesBegan)

一番はじめにタップした箇所の座標を取得します。これがViewの目的地の座標というわけです。

let after = touches.first!.location(in: self.view)

移動前のViewの座標も取得する必要があります。

let before = myView.center

xとyの変化量をそれぞれ求めます。(変化量というのは、どれぐらい値が増減したかを表すものです)
例えば、移動前の座標(10, 300)から移動後の座標(30, 200)に移動した場合のxとyの変化量Δx, Δyは
Δx = 30 - 10 = 20
Δy = 200 - 300 = -100
よって、変化量は(20, -100)となるわけです。

let deltaX = after.x - before.x
let deltaY = after.y - before.y

そして、求めた変化量がViewが移動するべき移動量になるので、CGAffineTransformでアニメーション付きで移動させてあげます。(CGAffineTransform

UIView.animate(withDuration: 0.3) {
    self.myView.transform = CGAffineTransform(translationX: deltaX, y: deltaY)
}

おわりに

おわりです。

0
1
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
1