objective-c uicollectionview uitapgesturerecognizer

objective c - Manejo de Tap Gesture en UICollectionView



objective-c uitapgesturerecognizer (1)

dado que no podía usar ningún marco para crear un álbum de fotos, estoy tratando de crear el mío usando Collection View, pero me quedé atrapado al principio.

Mi objetivo es mostrar todas las imágenes de mi servicio web en mi vista de colección, ya que todas se muestran, el siguiente paso es cuando alguien toca una celda, puedo abrirla en una nueva vista y también navegar entre todas.

aquí está el código básico que creé:

- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. [collectionController reloadData]; tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:nil action:@selector(touched)]; tapGesture.numberOfTapsRequired = 1; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } -(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{ return 1; } -(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{ return 6; } -(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{ static NSString *cellIdentifier = @"Cell"; CollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath]; [cell.imgCollection setImageWithURL:[NSURL URLWithString:@"http://sallescds.com.br/wp-content/uploads/2012/12/xepop-300x300.jpg"] placeholderImage:[UIImage imageNamed:@"placeholder.png"]]; [cell.imgCollection addGestureRecognizer:tapGesture]; return cell; } -(void)touched:(UIGestureRecognizer *)tap{ NSLog(@"the touch happened"); }

gracias chicos.


Un par de cosas no son correctas en tu código:

Primero , initWithTarget:action: no se debe pasar un valor nil para el objetivo. De los documentos :

objetivo

Un objeto que es el destinatario de mensajes de acción enviados por el receptor cuando reconoce un gesto. nil no es un valor válido .

En su caso, debe pasar self como objetivo porque desea enviar el mensaje touched: a la instancia actual de su clase.

Segundo , el selector que pasó a initWithTarget:action: es incorrecto. Usó @selector(touched) pero su implementación de método es - (void)touched:(UIGestureRecognizer *)tap; , qué selector es @selector(touched:) (mind the @selector(touched:) .

Recomiendo leer esta pregunta sobre los selectores si está confundido.

En tercer lugar , no puede adjuntar un solo UIGestureRecognizer a la vista múltiple (consulte esta pregunta SO ).

Entonces, para que funcione, podría crear un UITapGestureRecognizer por celda de recolección (tal vez en una subclase). O mejor aún, implemente su método UICollectionViewDelegate collectionView:didSelectItemAtIndexPath:

EDITAR - Cómo implementar collectionView:didSelectItemAtIndexPath: ::

- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. // Bind the collectionView''s delegate to your view controller // This could also be set without code, in your storyboard self.collectionView.delegate = self; } -(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView { return 1; } -(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section { return 6; } -(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{ static NSString *cellIdentifier = @"Cell"; UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath]; [cell.imgCollection setImageWithURL:[NSURL URLWithString:@"http://sallescds.com.br/wp-content/uploads/2012/12/xepop-300x300.jpg"] placeholderImage:[UIImage imageNamed:@"placeholder.png"]]; return cell; } // I implemented didSelectItemAtIndexPath:, but you could use willSelectItemAtIndexPath: depending on what you intend to do. See the docs of these two methods for the differences. - (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath { // If you need to use the touched cell, you can retrieve it like so UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath]; NSLog(@"touched cell %@ at indexPath %@", cell, indexPath); }