class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// UITapGestureRecognizer手势之单击
let rect = CGRect(x: 32, y: 80, width: 256, height: 256)
let imageView = UIImageView(frame: rect)//创建相应尺寸的图像视图对象
let image = UIImage(named:"cat")
imageView.image = image//使用加载的图片,创建一个图像视图
imageView.isUserInteractionEnabled = true //开启图像视图对象的交互功能
self.view.addSubview(imageView)
let guesture = UITapGestureRecognizer(target: self, action: #selector(ViewController.singleTap))//创建一个手势检测器,这是一个抽象类,他定义了所有手势的基本行为,并拥有6个子类,来检测发生在设备中的各种手势
imageView.addGestureRecognizer(guesture)//将创建的手势,指定给图像视图
UITapGestureRecognizer手势之长按
let rect = CGRect(x: 32, y: 80, width: 256, height: 256)
let imageView = UIImageView(frame: rect)
let image = UIImage(named: "cat")
imageView.image = image
imageView.isUserInteractionEnabled = true
self.view.addSubview(imageView)
let guesture = UILongPressGestureRecognizer(target: self, action: #selector(ViewController.longPress(_ :)))
imageView.addGestureRecognizer(guesture)
UITapGestureRecognizer手势之双击
let rect = CGRect(x: 32, y: 80, width: 256, height: 256)
let imageView = UIImageView(frame: rect)
let image = UIImage(named: "cat")
imageView.image = image
imageView.isUserInteractionEnabled = true
self.view.addSubview(imageView)
let guesture = UITapGestureRecognizer(target: self, action: #selector(ViewController.doubleTap))
guesture.numberOfTapsRequired = 2
guesture.numberOfTouchesRequired = 1
imageView.addGestureRecognizer(guesture)
}
@objc func singleTap()//创建一个方法 用于接收手势事件
{
//当接收到手势事件后,弹出一个提示窗口
let alertView = UIAlertController(title: "Information", message: "Single Tap", preferredStyle: UIAlertController.Style.alert)
//创建一个按钮,作为提示窗口中的(确定按钮),当用户点击该按钮时,将关闭提示窗口
let OKAction = UIAlertAction(title: "OK", style: .default, handler: {_ in
})
alertView.addAction(OKAction)//将确定按钮,添加到提示窗口中
self.present(alertView, animated: true,completion: nil)//在当前视图控制器中,展示提示窗口
}
@objc func longPress(_ gusture: UILongPressGestureRecognizer)
{
if(gusture.state == UIGestureRecognizer.State.began)
{
let alertView = UIAlertController(title: "Information", message: "Long Press", preferredStyle: UIAlertController.Style.alert)
let OKAction = UIAlertAction(title: "OK", style: .default, handler: {_ in
})
alertView.addAction(OKAction)
self.present(alertView,animated: true, completion: nil)
}
}
@objc func doubleTap()
{
let alertView = UIAlertController(title: "Information", message: "Double Tap", preferredStyle: UIAlertController.Style.alert)
let OKAction = UIAlertAction(title: "OK", style: .default, handler: {_ in
})
alertView.addAction(OKAction)
self.present(alertView,animated: true,completion: nil)
}
}