目錄:[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 //用於檢測發生在設備中的雙擊手勢 25 let guesture = UITapGestureRecognizer(target: self, action: #selector(ViewController.doubleTap(_:))) 26 //設置點擊次數爲2,模擬雙擊事件 27 guesture.numberOfTapsRequired = 2 28 //設置手勢爲單次雙擊事件 29 guesture.numberOfTouchesRequired = 1 30 //將建立的手勢指定給圖像視圖對象 31 imageView.addGestureRecognizer(guesture) 32 } 33 34 //建立一個方法,用來響應雙擊手勢的事件 35 @objc func doubleTap(_ guesture:UISwipeGestureRecognizer) 36 { 37 //當接收到手勢事件後,彈出一個窗口 38 let alertView = UIAlertController(title: "Information", message: "Double Tap", preferredStyle: UIAlertController.Style.alert) 39 //建立一個按鈕,做爲提示窗口中的【肯定】按鈕。 40 //當用戶點擊該按鈕時,將關閉提示窗口 41 let OKAction = UIAlertAction(title: "OK", style: .default, handler: nil) 42 alertView.addAction(OKAction) 43 //在當前視圖控制器中,展現提示窗口 44 self.present(alertView, animated: true, completion: nil) 45 } 46 }