2010-12-12 14 views
12

I estableció un UIImage para mi UIButton usando [myButton setImage:forState:]; y establece que es contentMode usando [[myButton imageView] setContentMode:UIViewContentModeScaleAspectFit]; Pero cuando se toca el botón, que se remonta a UIViewContentModeScaleToFill y se extiende hacia fuera mi imagen.UIButton contentMode ignorando cuando resaltada (adjustsImageWhenHighlighted)

usando adjustsImageWhenHighlighted corrige esto, pero luego pierdo el efecto de oscurecimiento, que me gustaría mantener.

¿Alguna sugerencia sobre cómo hacer frente a esto?

+0

tengo el mismo problema. empezando a pensar que no hay forma de evitar esto ... – jasongregori

Respuesta

2

mi solución a este problema (tal vez no eficiente, pero le da una oportunidad de personalizar el efecto de relieve, creo que se ve mejor que un estándar) es:

  • subclase UIButton por supuesto.
  • agregar propiedad @property (no atómico, retener) UIView * highlightView;
  • método de fijación de imagen (mi método, se puede utilizar el modo diferente importante establecer la propiedad adjustsImageWhenHighlighted)

    [self setImage:image forState:UIControlStateNormal]; 
    [self setAdjustsImageWhenHighlighted:NO]; 
    
  • anulación setHighlighted: Método de este modo:

    \- (void)setHighlighted:(BOOL)highlighted { 
        if (!highlightView) { 
         self.highlightView = [[[UIView alloc] initWithFrame:self.bounds] autorelease]; 
         self.highlightView.backgroundColor = [UIColor darkGrayColor]; 
         self.highlightView.alpha = 0.0; 
         [self addSubview:self.highlightView]; 
        } 
        if (highlighted) { 
         [UIView beginAnimations:@"highlight" context:nil]; 
         [UIView setAnimationDuration:0.2]; 
         highlightView.alpha = 0.5; 
         [UIView commitAnimations]; 
        } 
        else { 
         [UIView beginAnimations:@"highlight" context:nil]; 
         [UIView setAnimationDuration:0.2]; 
         highlightView.alpha = 0.0; 
         [UIView commitAnimations]; 
        } 
    } 
    

Estos trabajos para mí, pero si hay una manera mejor, estaré encantado de conocerla.

4
UIButton *imageBtn = [UIButton ... 
imageBtn.adjustsImageWhenHighlighted = NO; 

[imageBtn addTarget:self action:@selector(doSomething:) forControlEvents:UIControlEventTouchUpInside]; 

[imageBtn addTarget:self action:@selector(doHighlighted:) forControlEvents:UIControlEventTouchDown]; 
[imageBtn addTarget:self action:@selector(doHighlighted:) forControlEvents:UIControlEventTouchDragEnter]; 
    [imageBtn addTarget:self action:@selector(doCancelHighlighted:) forControlEvents:UIControlEventTouchDragExit]; 

-(void)doSomething:(UIButton *)button{ 
    ... 
    [self performSelector:@selector(doCancelHighlighted:) withObject:button afterDelay:0.2f]; 
} 

-(void)doHighlighted:(UIButton *)button{ 
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(5, 5, 300, 300)]; 
    imageView.backgroundColor = [UIColor blackColor]; 
    imageView.alpha = 0.7; 
    imageView.tag = 1000; 
    [button addSubview:imageView]; 
} 

-(void)doCancelHighlighted:(UIButton *)button{ 
    UIView *view = [button subviewWithTag:1000]; 
    [UIView animateWithDuration:0.2f animations:^{ 
     view.alpha = 0; 
    } completion:^(BOOL finished) { 
     [view removeFromSuperview];   
    }]; 
} 
+2

2 problemas: 1. nunca suelta la vista de la imagen en doHighlighted :, 2. subviewWithTag: debe ser viewWithTag :. También un consejo: en lugar de CGRectMake() en doHighlighted :, simplemente use button.bounds; Aparte de eso, esto funciona bien. – vakio

+0

realmente genial respuesta, gracias. –

0

Por alguna razón que se produce cuando se establece el modo de contenido después ajuste de la imagen para cualquier estado.

Asegúrese de configurar el modo de contenido antes de configurando las imágenes, de forma programática y en InterfaceBuilder también. Para solucionar esto en IB, asegúrese de eliminar todas las imágenes establecidas para todos los estados, configure el modo de contenido y luego vuelva a colocar las imágenes.

Eso lo arregló para mí.

Cuestiones relacionadas