目录:[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 }