[Swift2.0] UILabelとUIImageViewのタップイベント処理を実装する

  • 12
    いいね
  • 0
    コメント

tagを使ってタップイベントを処理します。

実装例(Swift2.0)

class MainViewController: UIViewController {
  @IBOutlet weak var sampleImageView: UIImageView!
  @IBOutlet weak var sampleNameLabel: UILabel!

  let tagSampleImageView = 1
  let tagSampleNameLabel = 2

  override func viewDidLoad() {
    super.viewDidLoad()

    sampleImageView.userInteractionEnabled = true
    sampleImageView.tag = tagSampleImageView

    sampleNameLabel.userInteractionEnabled = true
    sampleNameLabel.tag = tagSampleNameLabel
  }

  override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
    super.touchesEnded(touches, withEvent: event)
    for touch: UITouch in touches {
      let tag = touch.view!.tag
      switch tag {
      case tagSampleImageView, tagSampleNameLabel:
        print("tapped")
      default:
        break
      }
    }
  }
}