2009-07-17 11 views
5

Estoy tratando de cambiar entre dos vistas. Es fácil, el código está debajo, pero también quiero al mismo tiempo voltear el botón utilizado para realizar el giro.Botón para voltear el iPhone a la derecha (como iTunes)

Puede ver este comportamiento en la aplicación iPod cuando está reproduciendo una pista; al tocar el botón flip se alterna entre la portada y la lista de pistas, pero se gira el botón al mismo tiempo.

Esta es una página en el controlador de navegación, y el botón que quiero voltear es rightBarButtonItem.

Aquí está el código que tengo hasta ahora. Esto invierte la vista, pero no el botón derechoBarButton.

[UIView setAnimationBeginsFromCurrentState: YES]; 
[UIView setAnimationDuration: 0.5f]; 
[UIView setAnimationCurve: UIViewAnimationCurveEaseInOut]; 
showingBackside = !showingBackside; 
if (showingBackside) { 
    [UIView setAnimationTransition: UIViewAnimationTransitionFlipFromLeft 
          forView: self.view 
          cache: YES]; 
    [self.view addSubview: backside.view]; 
    [frontside.view removeFromSuperview]; 
} else { 
    [UIView setAnimationTransition: UIViewAnimationTransitionFlipFromRight 
          forView: self.view 
          cache: YES]; 
    [self.view addSubview: frontside.view]; 
    [backside.view removeFromSuperview]; 
} 
// flip image, too 
NSString *newImage = showingBackside ? @"backside.png" : @"frontside.png"; 
[(self.navigationItem.rightBarButtonItem) setImage: [UIImage imageNamed: newImage]]; 
[UIView commitAnimations]; 

(El código de la imagen de volteo aquí no compile; añadí después de tratar de explicar lo que estaba tratando de hacer.)

Dónde estoy corriendo en problemas es que quiero cambiar el el botón situado más a la derecha en el controlador de navegación, por lo que se invierte simultáneamente.

¿Cómo puedo hacer esto? ¿Qué vista puedo animar, y lo hago como parte del mismo bloque de animación o como uno separado? Cualquier consejo sería apreciado, definitivamente todavía no tengo un buen manejo de la animación.

Respuesta

5

Hay un poco de discusión here, pero la solución no es tan elegante.

Antes que nada, dado que UIBarButtonItem no es un descendiente de UIView, probablemente no pueda usar animaciones UIKit directamente en el UIBarButtonItem. Sin embargo, puede intentar configurar un customView y animar eso. Puedes usar el mismo bloque de animación.

+0

De la noche a la mañana Me di cuenta de que esta es una idea incluso mejor de la que le di. Creo que puedo capturar suficientes imágenes para hacer que UIImageView se vea y actuar como un botón, lo que significa que puedo lograrlo. Gracias. –

2

bien, aquí es lo que realmente hice para solucionar este problema:

Yo ya estaba usando una vista título personalizado. En lugar de usar rightBarButtonItem, amplié mi vista personalizada.

Creé una imagen de ambas caras del botón, junto con el marco de navegación, y las incrustó en la aplicación. En mi título de la vista, puse:

  • Un UIView que será mi reemplazo para el control de la derecha (lo llaman rightControl), posicionados adecuadamente.
  • Un botón sobre el UIView que responde a UIControlEventTouchUpInside y dispara mi flipSide:.

En tiempo de ejecución creo un UIImageView para cada estado. Puse ambos UIImageView s en rightControl, pero escondo el que no es el predeterminado. Cambio las banderas ocultas en flipSide: en un bloque de animación dedicado.

Increíblemente raro. Pero funciona.

+0

¿Puedes compartir algún código para esto? Luchando con algo similar – arnoapp

2

Simplemente use una UIView personalizada para el botón de navegación derecho que contiene dos botones para alternar.

Puede utilizar un enfoque directo para crear una UIView personalizada que se muestra como el elemento del botón de navegación derecho. Esta UIView debe contener los dos UIButtons entre los que desea intercambiar.Recuerda que los UIButtons también son UIView, por lo que pueden voltearse utilizando las mismas transiciones con las que se puede voltear una vista de UI normal y, por supuesto, se pueden aprovechar. Aquí hay un código de muestra que funciona:

Nota: utilizo una función de conveniencia para crear botones como una categoría personalizada de UIViewController (nota: también puede agregar este mismo código para crear una categoría personalizada para UIView, simplemente copie la misma líneas y reemplazar UIViewController con UIView) - Si desea usarlo también solo cree una categoría personalizada incluyendo este código a continuación, alternativamente puede crear los UIButtons como lo haría normalmente.

// create custom category for UIViewController to allow common button creation routine, add to .m or .mm file or add to a .h file and #import that .h file 
     @interface UIViewController (ButtonAndSelector) 
     - (UIButton *)createUIButtonWithImage:(UIImage *)image forState:(UIControlState)state withSelector:(SEL)selector usingFrame:(CGRect)buttonImageFrame; 
     @end 

     @implementation UIViewController (ButtonAndSelector) 
     - (UIButton *)createUIButtonWithImage:(UIImage *)buttonImage forState:(UIControlState)state withSelector:(SEL)selector usingFrame:(CGRect)buttonImageFrame 
     { 
      UIButton *button = [[UIButton alloc] initWithFrame:buttonImageFrame]; 
      [button setBackgroundImage:buttonImage forState:state]; 
      [button addTarget:self action:selector forControlEvents:UIControlEventTouchUpInside]; 
      [button setShowsTouchWhenHighlighted:YES]; 
      return button; 
     } 
     @end 

// add this to your .h file: 
     @property (strong, nonatomic) UIView *coverListView; 
     @property (strong, nonatomic) UIButton *listButton; 
     @property (strong, nonatomic) UIButton *coverButton; 

     - (void)animateCoverListButtonFlip; 

// add this to your .m or .mm file to synthesize the variables: 
     @synthesize coverListView; 
     @synthesize listButton; 
     @synthesize coverButton; 

// add this to your .m or .mm file in the viewDidLoad: 

     // setup right button bar (flips between list icon and coverart image) 
     self.coverListView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 32, 30)]; 
     self.coverListView.backgroundColor = [UIColor clearColor]; 
     self.coverListView.opaque = NO; 

     self.listButton = [self createUIButtonWithImage:[UIImage imageNamed:@"navbar_icon_tracklisting"] forState:UIControlStateNormal withSelector:@selector(showHideQueue) usingFrame:CGRectMake(0, 0, 32, 30)]; 
     self.listButton.backgroundColor = [UIColor clearColor]; 
     self.listButton.showsTouchWhenHighlighted = NO; 

     self.coverButton = [self createUIButtonWithImage:[UIImage imageNamed:@"default_coverart_small"] forState:UIControlStateNormal withSelector:@selector(showHideQueue) usingFrame:CGRectMake(0, 0, 32, 30)]; 
     [self.coverListView addSubview:self.coverButton]; // show coverButton by default 
      self.coverButton.showsTouchWhenHighlighted = NO; 

     UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.coverListView]; 
     [self.navigationItem setRightBarButtonItem:barButtonItem]; 


// add this to viewDidAppear if you want to flip the button when the screen appears like the build in iPod app does 
     [self animateCoverListButtonFlip]; 

// add this routine to flip the right navigation bar custom view/buttons 
     - (void)animateCoverListButtonFlip 
     { 
      [UIView beginAnimations:nil context:NULL]; 
      [UIView setAnimationDuration:0.75];  
      [UIView setAnimationTransition:([self.listButton superview] ? UIViewAnimationTransitionFlipFromLeft : UIViewAnimationTransitionFlipFromRight) forView:self.coverListView cache:YES]; 

      if ([self.listButton superview]) { 
       [self.listButton removeFromSuperview]; 
       [self.coverListView addSubview:self.coverButton]; 
      } else { 
       [self.coverButton removeFromSuperview]; 
       [self.coverListView addSubview:self.listButton]; 
      } 
      [UIView commitAnimations]; 
     } 

// when the playing album cover changes, remember to update the coverButton: 
     UIImage *artworkImage; // set this to the current playing album image 
     [self.coverButton setImage:artworkImage forState:UIControlStateNormal]; 

// don't forget to call the animateCoverListButtonFlip in the button click handler (shown above as showHideQueue) that shows and hides the cover/queue(list of album tracks0 - something like this: 

     - (void)showHideQueue 
     {  
      [self animateCoverListButtonFlip]; 

      /* replace the code below that is commented out here with your own code that transitions between your cover view and your list view of album tracks, this code shows my transition and references views that are not part of this example/answer, but you don't need those - you'll have your own cover view (musicPlayerView) and list view (musicQueueView) to flip between. 
      [UIView beginAnimations:nil context:NULL]; 
      [UIView setAnimationDuration:0.75]; 
      [UIView setAnimationTransition:([musicQueueView superview] ? UIViewAnimationTransitionFlipFromLeft : UIViewAnimationTransitionFlipFromRight) forView:self.contentView cache:YES]; 

      if ([musicQueueView superview]) { // if music queue is displayed 
       [musicQueueView removeFromSuperview]; 
       [self.contentView addSubview:musicPlayerView]; 
      } else { 
       [musicPlayerView removeFromSuperview]; 
       [self.contentView addSubview:musicQueueView]; 
       [[musicQueueView queueTableView] reloadData]; 
      } 
      [UIView commitAnimations];*/ 
     } 
Cuestiones relacionadas