1. 程式人生 > >[Swift通天遁地]三、手勢與圖表-(1)監聽螢幕上觸控事件的各種狀態

[Swift通天遁地]三、手勢與圖表-(1)監聽螢幕上觸控事件的各種狀態

本文將演示監聽螢幕上觸控事件的各種狀態。

在專案導航區,開啟檢視控制器的程式碼檔案【ViewController.swift】

現在開始編寫程式碼,監聽螢幕上的觸控事件的各種狀態。

 1 import UIKit
 2 
 3 class ViewController: UIViewController {
 4 
 5     override func viewDidLoad() {
 6         super.viewDidLoad()
 7         // Do any additional setup after loading the view, typically from a nib.
8 9 } 10 11 //新增一個方法,用來監聽手指按下時的事件 12 override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { 13 //當手指在螢幕上剛剛按下時,在控制檯輸出日誌資訊。 14 print("touchesBegan"); 15 } 16 17 //新增一個方法,用來監聽手指移動時的事件 18 override func touchesMoved(_ touches: Set<UITouch>, with event
: UIEvent?) { 19 //當手指在螢幕上剛剛按下並移動時,在控制檯輸出日誌資訊。 20 print("touchesMoved"); 21 } 22 23 //新增一個方法,用來監聽手指移動結束,離開螢幕時的事件 24 override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { 25 //當手指移動結束時,離開螢幕時,在控制檯輸出日誌資訊。 26 print("touchesEnded
"); 27 } 28 29 //新增一個方法,用來監聽手勢被取消的事件。例如手指子啊移動時,突然有電話接入時的情況 30 override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) { 31 //當手勢被取消時,在控制檯輸出日誌資訊。 32 print("touchesCancelled"); 33 } 34 35 override func didReceiveMemoryWarning() { 36 super.didReceiveMemoryWarning() 37 // Dispose of any resources that can be recreated. 38 } 39 }