¿Cómo puedo personalizar el estado de selección de mi subclase UICollectionViewCell?


Tengo una subclase UICollectionViewCell personalizada que sobrescribe initWithFrame: y layoutSubviews para configurar sus vistas. Sin embargo, ahora estoy tratando de hacer dos cosas con las que estoy teniendo problemas.

1) Estoy tratando de personalizar el estado de la UICollectionViewCell al momento de la selección. Por ejemplo, quiero cambiar una de las imágenes en un UIImageView en el UICollectionViewCell.

2) Quiero animar (rebote de luz) el UIImage en el UICollectionViewCell.

¿Puede alguien señalarme en la dirección correcta?

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    MyCollectionViewCell *cell = (MyCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
    [cell setSelected:YES];
}
Author: idmean, 2012-12-01

4 answers

Agregue un método público performSelectionAnimations a la definición de MyCollectionViewCell que cambie el UIImageView deseado y realice la animación deseada. Luego llámelo desde collectionView:didSelectItemAtIndexPath:.

Así que en MyCollectionViewCell.m:

- (void)performSelectionAnimations {
    // Swap the UIImageView
    ...

    // Light bounce animation
    ...
}

Y en su UICollectionViewController:

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    MyCollectionViewCell *cell = (MyCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
    [cell performSelectionAnimations];
}

Observe que he sacado la llamada a [cell setSelected:YES], ya que eso ya debería ser atendido por el UICollectionView. De la documentación:

La forma preferida de seleccionar la celda y resaltarla es usar los métodos de selección del objeto de vista de colección.

 17
Author: Jonathan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-17 16:09:46

En su subclase UICollectionViewCell personalizada, podría anular setSelected: de la siguiente manera:

- (void)setSelected:(BOOL)selected {
    [super setSelected:selected];

    if (selected) {
        [self animateSelection];
    } else {
        [self animateDeselection];
    }
}

He encontrado que en toques repetidos este método se llama a una celda incluso si ya está seleccionada, por lo que es posible que desee comprobar que realmente está cambiando el estado antes de disparar animaciones no deseadas.

 53
Author: thomh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-01-31 17:08:55

En su subclase personalizada UICollectionViewCell, puede implementar didSet en la propiedad isSelected.

Swift 3:

override var isSelected: Bool {
    didSet {
        if isSelected {
            // animate selection
        } else {
            // animate deselection
        }
    }
}

Swift 2:

override var selected: Bool {
    didSet {
        if self.selected {
            // animate selection
        } else {
            // animate deselection
        }
    }
}
 46
Author: Mike Sprague,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-21 16:08:46

Si desea mostrar animación en la selección, el siguiente método puede ser útil para usted:

 - (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
     NSLog(@"cell #%d was selected", indexPath.row);


     // animate the cell user tapped on
     UICollectionViewCell  *cell = [collectionView cellForItemAtIndexPath:indexPath];

     [UIView animateWithDuration:0.8
                           delay:0
                         options:(UIViewAnimationOptionAllowUserInteraction)
                      animations:^{
                          [cell setBackgroundColor:UIColorFromRGB(0x05668d)];
                      }
                      completion:^(BOOL finished){
                          [cell setBackgroundColor:[UIColor clearColor]];
                      }
      ];


 }
 2
Author: Gaurav,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-02-26 14:20:42