目錄:[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 = UILongPressGestureRecognizer(target: self, action:#selector(ViewController.longPress(_:))) 26 //將建立的手勢指定給圖像視圖對象 27 imageView.addGestureRecognizer(guesture) 28 } 29 30 //建立一個方法,用於接收長按手勢事件 31 @objc func longPress(_ gusture:UILongPressGestureRecognizer) 32 { 33 //首先檢測一下手勢事件的階段 34 if(gusture.state == UIGestureRecognizer.State.began) 35 { 36 //接收到手勢事件後,彈出一個窗口 37 let alertView = UIAlertController(title: "Information", message: "Long Press", preferredStyle: UIAlertController.Style.alert) 38 //建立一個按鈕,做爲提示窗口中的【肯定】按鈕。 39 //當用戶點擊該按鈕時,將關閉提示窗口 40 let OKAction = UIAlertAction(title: "OK", style: .default, handler: {_ in 41 42 }) 43 //將肯定按鈕添加到提示窗口中 44 alertView.addAction(OKAction) 45 //在當前視圖控制器中,展現提示窗口 46 self.present(alertView, animated: true, completion: nil) 47 } 48 } 49 }