Domanda

Ho un UIImageView, che voglio essere in grado di ridimensionare e ruotare, ecc.

Può un UIGestureRecognizer essere aggiunto alla UIImageView?

Vorrei aggiungere una rotazione e un pizzico riconoscitore ad un UIImageView che si verrebbe a creare in fase di esecuzione.

Come si fa ad aggiungere questi sistemi di riconoscimento?

È stato utile?

Soluzione

Controllare che userInteractionEnabled è YES sul UIImageView. Quindi è possibile aggiungere un sistema di riconoscimento gesto.

imageView.userInteractionEnabled = YES;
UIPinchGestureRecognizer *pgr = [[UIPinchGestureRecognizer alloc] 
    initWithTarget:self action:@selector(handlePinch:)];
pgr.delegate = self;
[imageView addGestureRecognizer:pgr];
[pgr release];
:
:
- (void)handlePinch:(UIPinchGestureRecognizer *)pinchGestureRecognizer
{
  //handle pinch...
}

Altri suggerimenti

Sì, un UIGestureRecognizer può essere aggiunto a un UIImageView. Come indicato nel altra risposta, è molto importante ricordarsi di consentire l'interazione utente sulla visualizzazione dell'immagine impostando la sua proprietà userInteractionEnabled a YES. UIImageView eredita da UIView, la cui interazione con l'utente proprietà è impostata su YES per impostazione predefinita, tuttavia, di proprietà di interazione con l'utente UIImageView è impostato su NO per impostazione predefinita.

UIImageView docs:

  

I nuovi oggetti di visualizzazione dell'immagine sono configurati per eventi utente disinteresse da   predefinito. Se si vuole eventi manico in una sottoclasse personalizzata di   UIImageView, è necessario modificare esplicitamente il valore della   userInteractionEnabled proprietà su Sì dopo aver inizializzato l'oggetto.

In ogni caso, il la maggior parte della risposta. Ecco un esempio di come creare una UIImageView con un UIPinchGestureRecognizer, un UIRotationGestureRecognizer e un UIPanGestureRecognizer.

Innanzitutto, in viewDidLoad, o un altro metodo di scelta, creare la visualizzazione di un'immagine, dare un'immagine, un frame e consentire la sua interazione con l'utente. Quindi creare i tre gesti come segue. Assicurarsi di utilizzare la loro proprietà delegato (molto probabilmente impostato su di sé). Questo sarà necessario per utilizzare molteplici gesti allo stesso tempo.

- (void)viewDidLoad
{
    [super viewDidLoad];

    // set up the image view
    UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"someImage"]];
    [imageView setBounds:CGRectMake(0.0, 0.0, 120.0, 120.0)];
    [imageView setCenter:self.view.center];
    [imageView setUserInteractionEnabled:YES]; // <--- This is very important

    // create and configure the pinch gesture
    UIPinchGestureRecognizer *pinchGestureRecognizer = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(pinchGestureDetected:)];
    [pinchGestureRecognizer setDelegate:self];
    [imageView addGestureRecognizer:pinchGestureRecognizer];

    // create and configure the rotation gesture
    UIRotationGestureRecognizer *rotationGestureRecognizer = [[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(rotationGestureDetected:)];
    [rotationGestureRecognizer setDelegate:self];
    [imageView addGestureRecognizer:rotationGestureRecognizer];

    // creat and configure the pan gesture
    UIPanGestureRecognizer *panGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGestureDetected:)];
    [panGestureRecognizer setDelegate:self];
    [imageView addGestureRecognizer:panGestureRecognizer];


    [self.view addSubview:imageView]; // add the image view as a subview of the view controllers view
}

Qui ci sono i tre metodi che verranno chiamati quando vengono rilevati i gesti sul vostro punto di vista. Al loro interno, si provvederà a controllare lo stato attuale del gesto, e se è sia nel iniziato o modificato UIGestureRecognizerState leggeremo proprietà scala / rotazione / traduzione del gesto, applicare che i dati a una trasformazione affine, applicare la trasformazione affine al visualizzazione dell'immagine, e quindi ripristinare l'gesti scala / rotazione / traslazione.

- (void)pinchGestureDetected:(UIPinchGestureRecognizer *)recognizer
{
    UIGestureRecognizerState state = [recognizer state];

    if (state == UIGestureRecognizerStateBegan || state == UIGestureRecognizerStateChanged)
    {
        CGFloat scale = [recognizer scale];
        [recognizer.view setTransform:CGAffineTransformScale(recognizer.view.transform, scale, scale)];
        [recognizer setScale:1.0];
    }
}

- (void)rotationGestureDetected:(UIRotationGestureRecognizer *)recognizer
{
    UIGestureRecognizerState state = [recognizer state];

    if (state == UIGestureRecognizerStateBegan || state == UIGestureRecognizerStateChanged)
    {
        CGFloat rotation = [recognizer rotation];
        [recognizer.view setTransform:CGAffineTransformRotate(recognizer.view.transform, rotation)];
        [recognizer setRotation:0];
    }
}

- (void)panGestureDetected:(UIPanGestureRecognizer *)recognizer
{
    UIGestureRecognizerState state = [recognizer state];

    if (state == UIGestureRecognizerStateBegan || state == UIGestureRecognizerStateChanged)
    {
        CGPoint translation = [recognizer translationInView:recognizer.view];
        [recognizer.view setTransform:CGAffineTransformTranslate(recognizer.view.transform, translation.x, translation.y)];
        [recognizer setTranslation:CGPointZero inView:recognizer.view];
    }
}

Infine e molto importante, avrete bisogno di utilizzare il UIGestureRecognizerDelegate metodo gestureRecognizer: shouldRecognizeSimultaneouslyWithGestureRecognizer per consentire i gesti al lavoro allo stesso tempo. Se queste tre gesti sono gli unici tre gesti che hanno questa classe assegnato come loro delegato, allora si può semplicemente tornare YES come illustrato di seguito. Tuttavia, se si dispone di gesti aggiuntivi che hanno questa classe assegnato come loro delegato, potrebbe essere necessario aggiungere la logica a questo metodo per determinare quale gesto è che prima di loro permettendo di lavorare tutti insieme.

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    return YES;
}

Non dimenticate di fare in modo che i tuoi conforme alla classe UIGestureRecognizerDelegate protocollo. Per fare ciò, assicurarsi che l'interfaccia simile a questa:

@interface MyClass : MySuperClass <UIGestureRecognizerDelegate>

Se si preferisce giocare con il codice in un progetto di esempio che lavora da soli, il progetto di esempio ho creato contenente questo codice può essere trovato qui .

Swift 4.2

myImageView.isUserInteractionEnabled = true
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(imageTapped))
tapGestureRecognizer.numberOfTapsRequired = 1
myImageView.addGestureRecognizer(tapGestureRecognizer)

e se battuto:

@objc func imageTapped(_ sender: UITapGestureRecognizer) {
   // do something when image tapped
   print("image tapped")
}

Swift 2.0 Soluzione

È possibile creare un colpetto, pizzico o strisciare gesto riconoscitore nello stesso maniero. Qui di seguito ti passeggiata attraverso 4 passi per ottenere il vostro riconoscitore installato e funzionante.

4 Passi

1). Eredita dal UIGestureRecognizerDelegate aggiungendolo alla tua firma classe.

class ViewController: UIViewController, UIGestureRecognizerDelegate {...}

2) di controllo trascinare dalla vostra immagine al vostro viewController per creare un IBOutlet:.

@IBOutlet weak var tapView: UIImageView!

3) Nel vostro viewDidLoad aggiungere il seguente codice:.

// 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). Crea la funzione che verrà chiamato quando il vostro sistema di riconoscimento gesto è sfruttato. (È possibile escludere la = nil se si sceglie).

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)
}

Il tuo codice finale dovrebbe essere simile a questo:

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)
    }
}

Ho appena fatto questo con swift4 aggiungendo 3 gesti insieme in un'unica vista

  1. UIPinchGestureRecognizer : zoom in e zoom out vista.
  2. UIRotationGestureRecognizer :. Ruotare la vista
  3. UIPanGestureRecognizer :. Trascinando la vista

Ecco il mio codice di esempio

class ViewController: UIViewController: UIGestureRecognizerDelegate{
      //your image view that outlet from storyboard or xibs file.
     @IBOutlet weak var imgView: UIImageView!
     // declare gesture recognizer
     var panRecognizer: UIPanGestureRecognizer?
     var pinchRecognizer: UIPinchGestureRecognizer?
     var rotateRecognizer: UIRotationGestureRecognizer?

     override func viewDidLoad() {
          super.viewDidLoad()
          // Create gesture with target self(viewcontroller) and handler function.  
          self.panRecognizer = UIPanGestureRecognizer(target: self, action: #selector(self.handlePan(recognizer:)))
          self.pinchRecognizer = UIPinchGestureRecognizer(target: self, action: #selector(self.handlePinch(recognizer:)))
          self.rotateRecognizer = UIRotationGestureRecognizer(target: self, action: #selector(self.handleRotate(recognizer:)))
          //delegate gesture with UIGestureRecognizerDelegate
          pinchRecognizer?.delegate = self
          rotateRecognizer?.delegate = self
          panRecognizer?.delegate = self
          // than add gesture to imgView
          self.imgView.addGestureRecognizer(panRecognizer!)
          self.imgView.addGestureRecognizer(pinchRecognizer!)
          self.imgView.addGestureRecognizer(rotateRecognizer!)
     }

     // handle UIPanGestureRecognizer 
     @objc func handlePan(recognizer: UIPanGestureRecognizer) {    
          let gview = recognizer.view
          if recognizer.state == .began || recognizer.state == .changed {
               let translation = recognizer.translation(in: gview?.superview)
               gview?.center = CGPoint(x: (gview?.center.x)! + translation.x, y: (gview?.center.y)! + translation.y)
               recognizer.setTranslation(CGPoint.zero, in: gview?.superview)
          }
     }

     // handle UIPinchGestureRecognizer 
     @objc func handlePinch(recognizer: UIPinchGestureRecognizer) {
          if recognizer.state == .began || recognizer.state == .changed {
               recognizer.view?.transform = (recognizer.view?.transform.scaledBy(x: recognizer.scale, y: recognizer.scale))!
               recognizer.scale = 1.0
         }
     }   

     // handle UIRotationGestureRecognizer 
     @objc func handleRotate(recognizer: UIRotationGestureRecognizer) {
          if recognizer.state == .began || recognizer.state == .changed {
               recognizer.view?.transform = (recognizer.view?.transform.rotated(by: recognizer.rotation))!
               recognizer.rotation = 0.0
           }
     }

     // mark sure you override this function to make gestures work together 
     func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
         return true
     }

}

Tutta la domanda, basta digitare al commento. grazie

SWIFT 3 Esempio

override func viewDidLoad() {

         self.backgroundImageView.addGestureRecognizer(
             UITapGestureRecognizer.init(target: self, action:
                 #selector(didTapImageview(_:))
             )
         )
         self.backgroundImageView.isUserInteractionEnabled = true
     }

     func didTapImageview(_ sender: Any) {
          // do something
     }
}

Non ci sono delegati gesto recongnizer o altre implementazioni, se necessario.

È anche possibile trascinare un riconoscitore rubinetto gesto alla visualizzazione dell'immagine in Storyboard. Quindi creare un'azione da Ctrl + trascinare per il codice ...

Per amante blocchi è possibile utilizzare ALActionBlocks per aggiungere l'azione dei gesti in blocco

__weak ALViewController *wSelf = self;
imageView.userInteractionEnabled = YES;
UITapGestureRecognizer *gr = [[UITapGestureRecognizer alloc] initWithBlock:^(UITapGestureRecognizer *weakGR) {
    NSLog(@"pan %@", NSStringFromCGPoint([weakGR locationInView:wSelf.view]));
}];
[self.imageView addGestureRecognizer:gr];
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top