[Xcode 實際操做]2、視圖與手勢-(10)UITapGestureRecognizer手勢之單擊

目錄:[Swift]Xcode實際操做html

本文將演示使用視圖的手勢功能,完成視圖的交互操做。ide

 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         //初始化一個原點在(32,80),尺寸爲(256,256)的矩形常量,做爲圖像視圖的顯示區域
 9         let rect = CGRect(x: 32, y: 80, width: 256, height: 256)
10         //建立一個相應尺寸的圖像視圖對象
11         let imageView = UIImageView(frame: rect)
12         
13         //從資源文件夾中,讀取項目中的一張圖片
14         let image = UIImage(named: "Strengthen")
15         //使用加載的圖片,建立一個圖像視圖
16         imageView.image = image
17         
18         //開啓圖像視圖對象的交互功能
19         imageView.isUserInteractionEnabled = true
20         //將圖像視圖添加到當前視圖控制器的根視圖
21         self.view.addSubview(imageView)
22         
23         //建立一個手勢檢測類,這是一個抽象類,它定義了全部手勢的基本行爲,
24         //並擁有6哥子類,來檢測發生在設備中的各類手勢
25         let guesture = UITapGestureRecognizer(target: self,
26                                               action: #selector(ViewController.singleTap(_:)))
27         //將建立的手勢指定給圖像視圖
28         imageView.addGestureRecognizer(guesture)
29     }
30     
31     //建立一個方法,用於接收手勢事件。
32     @objc func singleTap(_ gusture:UITapGestureRecognizer)
33     {
34         //在控制檯輸出手勢須要匹配的屏幕被觸碰的次數,它的默認值爲1
35         print(gusture.numberOfTapsRequired)
36         //在控制檯輸出手勢包含的手指的數量,默認值也是1
37         print(gusture.numberOfTouchesRequired)
38         //當接收到手勢事件後,彈出一個窗口
39         let alertView = UIAlertController(title: "Information", message: "Single Tap", preferredStyle: UIAlertController.Style.alert)
40         //建立一個按鈕,做爲提示窗口中的【肯定】按鈕。
41         //當用戶點擊該按鈕時,將關閉提示窗口
42         let OKAction = UIAlertAction(title: "OK", style: .default, handler: {_ in
43             
44         })
45         //將肯定按鈕添加到提示窗口中
46         alertView.addAction(OKAction)
47         //在當前視圖控制器中,展現提示窗口
48         self.present(alertView, animated: true, completion: nil)
49     }
50 }
相關文章
相關標籤/搜索