LoginSignup
1

More than 5 years have passed since last update.

Swiftについての覚書2

Posted at

各タップの検知の仕方について

まずはタップを検知する画像を作成

    // UIImageViewを作成
    let touchImageView = UIImageView(frame: CGRectMake(20,20,100,120))
    // 画像を設定
    let touchImage = UIImage(named: "kuroneko.gif")
    // 画像をUIImageViewに設定する
    touchImageView.image = touchImage
    // 画像の表示する座標を指定する.
    touchImageView.layer.position = CGPoint(x: 100, y: 200.0)
    // viewに追加
    self.view.addSubview(touchImageView)
    // タップを検知するよう設定
    touchImageView.userInteractionEnabled = true

userInteractionEnabled = true でタップを検知するようになります。

タップ

/*
 タッチを感知した際に呼ばれるメソッド.
 */
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    print("タップされた!")
}

タップを検知したら自動でtouchesBeganが呼び出されます。

ダブルタップ

    // ダブルタップの設定
    let doubleTapGesture: UITapGestureRecognizer = UITapGestureRecognizer(target: self
        , action:#selector(doubleTap(_:)))
    doubleTapGesture.numberOfTapsRequired = 2
    self.touchImageView.userInteractionEnabled = true
    self.touchImageView.addGestureRecognizer(doubleTapGesture)

  // ダブルタップ検知時の動作
  func doubleTap(gesture: UITapGestureRecognizer) -> Void {
      print("ダブルタップされた!")
  }

長押し

    // 長押しの設定
    let longPress = UILongPressGestureRecognizer(target: self, action: #selector(pressedLong(_:)))
    self.touchImageView.addGestureRecognizer(longPress)

  // 長押し検知時の動作
  func pressedLong(sender: UILongPressGestureRecognizer!) {
      print("長押しされた!")
  }

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
1