UIGestureRecognizer on UIImageView

前端 未结 8 1116
南旧
南旧 2020-11-28 01:32

I have a UIImageView, which I want to be able to resize and rotate etc.

Can a UIGestureRecognizer be added to the UIImageView?

8条回答
  •  执笔经年
    2020-11-28 02:28

    Swift 2.0 Solution

    You create a tap, pinch or swipe gesture recognizer in the same manor. Below I'll walk you through 4 steps to getting your recognizer up and running.

    4 Steps

    1.) Inherit from UIGestureRecognizerDelegate by adding it to your class signature.

    class ViewController: UIViewController, UIGestureRecognizerDelegate {...}
    

    2.) Control drag from your image to your viewController to create an IBOutlet:

    @IBOutlet weak var tapView: UIImageView!
    

    3.) In your viewDidLoad add the following code:

    // create an instance of UITapGestureRecognizer and tell it to run 
    // an action we'll call "handleTap:"
    let tap = UITapGestureRecognizer(target: self, action: Selector("handleTap:"))
    // we use our delegate
    tap.delegate = self
    // allow for user interaction
    tapView.userInteractionEnabled = true
    // add tap as a gestureRecognizer to tapView
    tapView.addGestureRecognizer(tap)
    

    4.) Create the function that will be called when your gesture recognizer is tapped. (You can exclude the = nil if you choose).

    func handleTap(sender: UITapGestureRecognizer? = nil) {
        // just creating an alert to prove our tap worked!
        let tapAlert = UIAlertController(title: "hmmm...", message: "this actually worked?", preferredStyle: UIAlertControllerStyle.Alert)
        tapAlert.addAction(UIAlertAction(title: "OK", style: .Destructive, handler: nil))
        self.presentViewController(tapAlert, animated: true, completion: nil)
    }
    

    Your final code should look something like this:

    class ViewController: UIViewController, UIGestureRecognizerDelegate {
    
        @IBOutlet weak var tapView: UIImageView!
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            let tap = UITapGestureRecognizer(target: self, action: Selector("handleTap:"))
            tap.delegate = self
            tapView.userInteractionEnabled = true
            tapView.addGestureRecognizer(tap)
        }
    
        func handleTap(sender: UITapGestureRecognizer? = nil) {
            let tapAlert = UIAlertController(title: "hmmm...", message: "this actually worked?", preferredStyle: UIAlertControllerStyle.Alert)
            tapAlert.addAction(UIAlertAction(title: "OK", style: .Destructive, handler: nil))
            self.presentViewController(tapAlert, animated: true, completion: nil)
        }
    }
    

提交回复
热议问题