1. 程式人生 > >[Swift通天遁地]三、手勢與圖表-(2)監聽手勢事件自由拖動影象檢視

[Swift通天遁地]三、手勢與圖表-(2)監聽手勢事件自由拖動影象檢視

本文將演示監聽手勢事件,使圖片可以自由被拖動。

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

現在開始編寫程式碼,實現監聽手勢事件自由拖動的影象檢視。

 1 import UIKit
 2 
 3 class ViewController: UIViewController
 4 {
 5     //給類新增一個屬性,作為被拖動的影象檢視。
 6     var imageView : UIImageView!
 7     //新增一個屬性,用於判斷圖片是否被按下。
 8     var isTouchInImageView : Bool = false
9 10 override func viewDidLoad() 11 { 12 super.viewDidLoad() 13 // Do any additional setup after loading the view, typically from a nib. 14 15 //從專案中載入圖片資源 16 let image = UIImage(named: "Star") 17 //使用影象檢視顯示載入的圖片 18 self.imageView = UIImageView(image: image)
19 //將影象檢視新增到根檢視中 20 self.view.addSubview(self.imageView) 21 } 22 23 //新增一個方法,用來監聽手指按下時的事件 24 override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) 25 { 26 //可能時多個手指同事按下, 27 //這裡獲取第一個觸控物件。 28 let touch = touches.first
29 //獲得觸控物件的座標 30 let touchPoint = touch?.location(in: self.view) 31 32 //獲得影象檢視的顯示區域 33 let imageViewFrame = self.imageView.frame 34 //獲得影象顯示區域的左上角的座標 35 let minX = imageViewFrame.origin.x 36 let minY = imageViewFrame.origin.y 37 //獲得影象顯示區域的右下角的座標 38 let maxX = minX + imageViewFrame.size.width 39 let maxY = minY + imageViewFrame.size.height 40 //將觸控位置的座標,和左上角以及右下角的座標進行比較, 41 //從而判斷觸控的位置是否位於影象的區域。 42 if (touchPoint?.x)! >= minX && (touchPoint?.y)! <= maxX && (touchPoint?.y)! >= minY && (touchPoint?.y)! <= maxY 43 { 44 //當觸控在影象區域時,設定布林屬性的值為真, 45 isTouchInImageView = true; 46 //然後在控制檯輸出日誌資訊。 47 print("You got a star."); 48 } 49 } 50 51 //新增一個方法,用來監聽手指移動時的事件 52 override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) 53 { 54 //判斷當觸控位置不在影象區域時,不再執行後方的程式碼。 55 if !isTouchInImageView 56 { 57 return; 58 } 59 //獲取第一個觸控物件 60 let touch = touches.first 61 //獲得觸控物件的座標 62 let touchPoint = touch?.location(in: self.view) 63 //獲得觸控物件在上一個位置時的座標 64 let touchPrePoint = touch?.previousLocation(in: self.view) 65 //計算兩個座標之間的偏移距離 66 let disX = (touchPoint?.x)! - (touchPrePoint?.x)! 67 let disY = (touchPoint?.y)! - (touchPrePoint?.y)! 68 69 //獲得影象檢視中心點的座標 70 var centerPoint = self.imageView.center 71 //然後將該座標和偏移距離相加,作為影象檢視新的位置 72 centerPoint.x += disX 73 centerPoint.y += disY 74 //重新整理影象檢視中心點的座標 75 self.imageView.center = centerPoint 76 } 77 78 //新增一個方法,用來監聽手指移動結束時的事件。 79 override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) 80 { 81 //當手指移開螢幕時,設定布林屬性的值為假。 82 isTouchInImageView = false; 83 } 84 85 override func didReceiveMemoryWarning() { 86 super.didReceiveMemoryWarning() 87 // Dispose of any resources that can be recreated. 88 } 89 }