2011-07-05 11 views
20

En mi vista principal, hago alguna acción de gestos que hace que se muestre una nueva vista. En este momento quiero atenuar todo el fondo (excepto esta nueva vista) como una buena práctica de UI. En HTML, Javascript parece que sí, ¿cómo obtengo el mismo efecto en iOS?iOS Fondo atenuado cuando se muestra una vista

enter image description here

Respuesta

33

Coloque una UIView sobre el fondo, establezca su fondo a [UIColor blackColor] y establezca su opacidad a como 0,6. A continuación, agregue ese UIView a la vista principal.

Esto atenuará el fondo Y interceptará los toques a los controles de fondo.

+0

¿Puede hacer ese diseño en el constructor de interfaz, luego simplemente ocultarlo por programación hasta que lo desee? ¿O de alguna manera interferirá incluso cuando esté oculto? – ToolmakerSteve

5

Aunque la sugerencia de Dan está en el objetivo, no puede usar un controlador de vista modal en este caso porque un modal típico cubre toda la pantalla, bloqueando el controlador de vista principal, incluso si tiene el fondo de su vista como transparente (' Veremos lo que tengas en la ventana UI de la aplicación).

Si está haciendo esto en el iPad, hay 2 estilos de presentación modal (UIViewModalPresentationStylePageSheet y UIViewModalPresentationStyleFormSheet) que pueden hacer algo similar, pero que no funcionarán en un iPhone o iPod Touch.

Agregue la vista "sombra", con el fondo oscuro y la opacidad parcial y cualquier vista que desee que esté en primer plano, a la vista del controlador de vista directamente. Puede animarlos mediante el uso de bloques de animación UIView estándar o CoreAnimation.

Otra nota, si desea interceptar toques a esa vista de sombra puede hacer que sea un botón gigante, subclase UIView para anular uno de los métodos táctiles como touchesEnded: o cambiarlo a un UIControl que puede recibir eventos táctiles como un UIButton, pero sin las opciones adicionales para texto, sombras, estados, etc.

+3

Tiene razón en que dije "modal" en mi respuesta. Realmente no quise decir una visión "presentada de forma modal" de ninguna manera formal. Estás construyendo tu propia vista modal, básicamente. –

1

Las dos respuestas anteriores funcionan si la nueva vista tiene su propio "fondo", es decir, no tiene transparencia. El problema que me condujo aquí no puede resolverse de esa manera, sin embargo, lo que estaba tratando de hacer es esto: estoy ejecutando un AVCaptureSession en mi pantalla con el AVCaptureVideoPreviewLayer habitual para mostrar el video en tiempo real. Quiero seleccionar una parte de la pantalla (para luego hacer algo solo con esta parte), y cuando esta parte está seleccionada quiero atenuar el resto de la vista previa del video. Esto es lo que parece:

Así es como he resuelto lo siguiente: Una nueva vista se crea en función de donde se toca la pantalla y se agrega como una vista secundaria de la opinión de previsualización de vídeo. Luego, creo 4 subvistas rectangulares adicionales que no se superponen con el color de fondo y la opacidad antes mencionados para cubrir el resto de la pantalla. Necesito explícitamente todas estas vistas no para ser subvistas de la vista principal, porque necesito la capacidad de tocar la pantalla en otro lugar y cambiar el área seleccionada.

Estoy seguro de que hay formas más elegantes de resolver esto, así que si alguien sabe cómo, por favor, comenten ...

1
#import <UIKit/UIKit.h> 

@interface ViewController : UIViewController<UIGestureRecognizerDelegate> 
{ 
    UIView *mainView; 
    UIView *dimBackgroundUIView; 
    UIView *customView; 

    UIButton *btn; 
} 

@end 


#import "ViewController.h" 

@interface ViewController() 

@end 

@implementation ViewController 

- (void)viewDidLoad { 
    [super viewDidLoad]; 

    mainView = [[UIView alloc] init]; 
    mainView.backgroundColor = [UIColor whiteColor]; 
    [self.view addSubview:mainView]; 
    [self addConstraintsForMainView]; 

    btn = [[UIButton alloc] initWithFrame:CGRectMake(200, 200, 100, 30)]; 
    [btn setTitle:@"Button" forState:UIControlStateNormal]; 
    [btn setBackgroundColor:[UIColor blueColor]]; 
    [btn addTarget:self action:@selector(showCustomView_Action:) forControlEvents:UIControlEventTouchUpInside]; 
    [mainView addSubview:btn]; 

    dimBackgroundUIView = [[UIView alloc] init]; 
    dimBackgroundUIView.backgroundColor = [UIColor blackColor]; 
    dimBackgroundUIView.alpha = 0.2; 
} 

-(void)removeCustomViewsFromSuperView { 

    if(dimBackgroundUIView) 
     [dimBackgroundUIView removeFromSuperview]; 

    if(customView) 
     [customView removeFromSuperview]; 
} 

- (void)didReceiveMemoryWarning { 
    [super didReceiveMemoryWarning]; 
    // Dispose of any resources that can be recreated. 
} 

- (IBAction)showCustomView_Action:(id)sender { 

    customView = [[UIView alloc] initWithFrame:CGRectMake(100, 200, 80, 80)]; 
    customView.backgroundColor = [UIColor redColor]; 

    [self.view addSubview:dimBackgroundUIView]; 
    [self addConstraintsForDimView]; 

    [self.view addSubview:customView]; 

    UITapGestureRecognizer *tapped = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(removeCustomViewsFromSuperView)]; 
    tapped.delegate=self; 
    tapped.numberOfTapsRequired = 1; 
    [customView addGestureRecognizer:tapped]; 
} 

-(void) addConstraintsForDimView { 

    [dimBackgroundUIView setTranslatesAutoresizingMaskIntoConstraints:NO]; 

    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:dimBackgroundUIView attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeft multiplier:1 constant:0]]; 

    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:dimBackgroundUIView attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeRight multiplier:1 constant:0]]; 

    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:dimBackgroundUIView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTop multiplier:1 constant:0]]; 

    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:dimBackgroundUIView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeBottom multiplier:1 constant:0]]; 
} 

-(void) addConstraintsForMainView { 

    [mainView setTranslatesAutoresizingMaskIntoConstraints:NO]; 

    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:mainView attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeft multiplier:1 constant:0]]; 

    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:mainView attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeRight multiplier:1 constant:0]]; 

    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:mainView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTop multiplier:1 constant:0]]; 

    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:mainView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeBottom multiplier:1 constant:0]]; 
} 

@end 

nota: se puede optimizar el código mediante el uso de la interfaz gráfica de Xcode, pero que tenía que escribir código de programación para poder probarlo

por lo que la idea es:

  1. cree UIView asígnele el nombre que desee (dimBackgroundUIView) que establezca el color de fondo como negro y configure alfa en 0.1 o 0.2 o ....
  2. agregue esta 2 línea de código cuando necesite atenuar el fondo: [self.view addSubview: dimBackgroundUIView]; [self addConstraintsForDimView];
  3. y agregue esta 2 línea de código cuando desee eliminar el fondo de atenuación : if (dimBackgroundUIView) [dimBackgroundUIView removeFromSuperview];
Cuestiones relacionadas