Swift 觸控事件與手勢辨識 (UITapGestureRecognizer) 是 iOS 開發中常見的功能,它可以讓開發者在 App 中增加觸控事件與手勢辨識的功能,讓 App 的使用者可以更輕鬆的操作 App。本文將介紹如何使用 Swift 來實現 UITapGestureRecognizer 的功能。

首先,我們需要在 Storyboard 中建立一個 UIView,並將它拖曳到 ViewController 中,然後將它的 Class 設定為 UIView,並將它的 Identifier 設定為 myView

接著,我們需要在 ViewController 中建立一個 UITapGestureRecognizer 物件,並將它指定給剛剛建立的 UIView,以下是程式碼:

let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap))
let myView = self.view.viewWithTag(1) as! UIView
myView.addGestureRecognizer(tapGesture)

接著,我們需要在 ViewController 中建立一個 handleTap 的函式,以下是程式碼:

@objc func handleTap(sender: UITapGestureRecognizer) {
    // 在這裡寫入你想要執行的程式碼
}

最後,我們就可以在 handleTap 函式中寫入我們想要執行的程式碼,例如:

@objc func handleTap(sender: UITapGestureRecognizer) {
    let alertController = UIAlertController(title: "提示", message: "您已經按下 UIView", preferredStyle: .alert)
    let okAction = UIAlertAction(title: "確定", style: .default, handler: nil)
    alertController.addAction(okAction)
    self.present(alertController, animated: true, completion: nil)
}

以上就是如何使用 Swift 來實現 UITapGestureRecognizer 的功能,使用 UITapGestureRecognizer 可以讓開發者在 App 中增加觸控事件與手勢辨識的功能,讓 App 的使用者可以更輕鬆的操作 App。

推薦閱讀文章

UIGestureRecognizer 手勢辨識
Swift 觸控事件與手勢辨識 (UITapGestureRecognizer)
iOS開發之UIGestureRecognizer手勢辨識
Swift UIGestureRecognizer 手勢辨識
iOS開發之UIGestureRecognizer手勢辨識</a

延伸閱讀本站文章

更多swift相關文章

推薦學習youtube影片

IOS多点触控与手势识别 10 10 自定义手势识别器及使用

Swift 觸控事件與手勢辨識 (UITapGestureRecognizer)

Categorized in:

Tagged in:

,