AI Engineering Service

AI Engineering Serviceの公式ブログです。開発者のプライベートな内容を含みます。

【Swift5】UILabelのタッチイベントを拾って処理をする

f:id:ibarakito:20190723235723p:plain

UIButton以外のオブジェクトに対してタッチイベントを拾いたい場合があると思います。
その場合、以下のように処理します。

override func touchesBegan(_ touches: Set<UITouch>,with event: UIEvent?){
    print("touched")
    //myLabelはタッチ判定をしたいUILabel
    if touchedLabel(touches: touches,view:myLabel){
      print("画面遷移など")
      return
    }
}

//タッチしたビューと指定したビューが一致した時、trueが返る
func touchedLabel(touches: Set<UITouch>, view:UILabel)->Bool{
    //全指のタッチについて処理
    for touch: AnyObject in touches {
        let t: UITouch = touch as! UITouch
        if t.view?.tag == view.tag {
            return true
        } else {
            return false
        }
    }
    return false
}

今回はUILabelについて書きましたが、他のクラスについても同様に書けます。UILabelをタップして画面遷移、は汎用性のあるコードなので参考にしてみてください。

プライバシーポリシー / お問い合わせ