LoginSignup
21
29

More than 5 years have passed since last update.

Swift:タッチイベントの際にタッチした座標を取得する方法2通り

Last updated at Posted at 2018-02-05

はじめに

タッチイベントの際指が触れている座標を知りたくなること、よくあると思います。備忘録としてタッチした座標を取得する方法を2通りまとめておきます。

1つ目の方法:UIResponder編

タッチイベントといえば、touchesBegantouchesMovedtouchesEnded三兄弟をよく使いますね。

基本

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    let touch = touches.first! //このタッチイベントの場合確実に1つ以上タッチ点があるので`!`つけてOKです
    let location = touch.location(in: self.view) //in: には対象となるビューを入れます
    Swift.print(location)
}

特定のビューに触れている全てのタッチ座標を調べたい場合

@IBOutlet weak var myView: UIView!

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    for touch in touches {
        let location = touch.location(in: myView)
        Swift.print(location)
    }
}

全域の全てのタッチ座標を調べたい場合

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let allTouches = event?.allTouches {
        for touch in allTouches {
            let location = touch.location(in: self.view) //一番親のビュー
            Swift.print(location)
        }
    }
}

2つ目の方法:UIControlEvents編

タッチイベントといえば、touchUpInsideとかtouchDownとかもありますよね。

@IBOutlet weak var myBtn: UIButton!

init() { //ViewDidLoadとか何かしらの初期化フェーズにて
    myBtn.addTarget(self, action: #selector(self.down(_:forEvent:)), for: .touchUpInside)
}

@objc func down(_ sender: UIButton, forEvent event: UIEvent) {
    let touches = event.touches(for: sender)
    let location = touches!.first!.location(in: sender)
    Swift.print(location)
}

※Swift4から#selector使う時はメソッドに@objcを明示的につけなくてはならなくなったので注意

21
29
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
21
29