2009-06-26 8 views

Respuesta

109

El enfoque más simple es tener dos vistas que pueden alternar su visibilidad para indicar qué vista se ha seleccionado. Aquí hay un código de ejemplo de cómo se puede hacer, definitivamente no es una forma optimizada para manejar los puntos de vista, pero sólo para demostrar cómo se puede utilizar el UISegmentControl para alternar la vista visible:

- (IBAction)segmentSwitch:(id)sender { 
    UISegmentedControl *segmentedControl = (UISegmentedControl *) sender; 
    NSInteger selectedSegment = segmentedControl.selectedSegmentIndex; 

    if (selectedSegment == 0) { 
    //toggle the correct view to be visible 
    [firstView setHidden:NO]; 
    [secondView setHidden:YES]; 
    } 
    else{ 
    //toggle the correct view to be visible 
    [firstView setHidden:YES]; 
    [secondView setHidden:NO]; 
    } 
} 


Por supuesto, puede volver a factorizar el código para ocultar/mostrar la vista correcta.

+4

'definitivamente no es una forma optimizada para manejar los puntos de vista ' - ¿por qué? –

+3

@ AdamWaite porque todas las vistas deben almacenarse en la memoria de forma permanente. Si sus vistas son demasiado complicadas y/o contienen muchos otros elementos, esto afectará el rendimiento general. Esa pieza de código podría ser refactorizada también. – Stas

+0

@Stas Tiene razón, es mejor dividir la lógica entre múltiples controladores de vista, cada uno responsable de sus propias acciones y comportamientos –

17

O si es una tabla, puede volver a cargar la tabla y en cellForRowAtIndex, rellene la tabla desde diferentes orígenes de datos según la opción de segmento seleccionada.

7

Una idea es hacer que la vista con los controles segmentados tenga una vista de contenedor que llene con las diferentes subvistas (agregar como una única subvista de la vista de contenedor cuando se alternan los segmentos). Incluso puede tener controladores de vista separados para esas subvistas, aunque debe reenviar métodos importantes como "viewWillAppear" y "viewWillDisappear" si los necesita (y tendrán que saber a qué controlador de navegación están).

Por lo general, funciona bastante bien porque puede diseñar la vista principal con contenedor en IB, y las subcarpetas llenarán cualquier espacio que el contenedor les permita tener (asegúrese de que sus máscaras de autoresize estén configuradas correctamente).

45

En mi caso, mis vistas son bastante complejas y no puedo simplemente cambiar la propiedad oculta de diferentes vistas, ya que ocuparía demasiada memoria.

He intentado varias soluciones y ninguna de ellas funcionó para mí, ni se realizó de forma errática, especialmente con el titleView de la navBar que no siempre muestra segmentedControl al pulsar/abrir vistas.

Encontré esta publicación en el blog sobre el problema que explica cómo hacerlo de la manera adecuada. Parece que tuvo la ayuda de los ingenieros de Apple en WWDC'2010 para encontrar esta solución.

http://redartisan.com/2010/6/27/uisegmented-control-view-switching-revisited

La solución en este enlace es sin duda la mejor solución que he encontrado sobre el tema hasta ahora. Con un poco de ajuste también funcionó bien con una barra de pestañas en la parte inferior

+0

Gracias por el gran descubrimiento. Definitivamente una solución agradable y elegante para esta metodología. – Shiun

+1

Traté de hacer que esto funcione correctamente con la barra de herramientas en la parte inferior sin éxito, http://stackoverflow.com/questions/4748120/uisegmentedcontroller-to-switch-between-uiviewcontrollers-calendar-app-style ¿Puede ayudarme por favor? ? – Erik

+0

¿Hay alguna manera de tener una animación horizontal entre las Vistas? ¿O solo funciona sin animación? – aneuryzm

3

Trate de usar SNFSegmentedViewController, un componente de código abierto que hace exactamente lo que está buscando con una configuración como UITabBarController.

2

Asignar .H en

UISegmentedControl *lblSegChange; 

- (IBAction)segValChange:(UISegmentedControl *) sender 

Declare.M

- (IBAction)segValChange:(UISegmentedControl *) sender 
{ 

if(sender.selectedSegmentIndex==0) 
{ 
    viewcontroller1 *View=[[viewcontroller alloc]init]; 
    [self.navigationController pushViewController:view animated:YES]; 
} 
else 
{ 
    viewcontroller2 *View2=[[viewcontroller2 alloc]init]; 
    [self.navigationController pushViewController:view2 animated:YES]; 
} 
} 
2

De la respuesta de @Ronnie Liew, creo esto:

// 
// ViewController.m 
// ResearchSegmentedView 
// 
// Created by Ta Quoc Viet on 5/1/14. 
// Copyright (c) 2014 Ta Quoc Viet. All rights reserved. 
// 
#define SIZE_OF_SEGMENT 56 
#import "ViewController.h" 

@interface ViewController() 

@end 

@implementation ViewController 
@synthesize theSegmentControl; 
UIView *firstView; 
UIView *secondView; 
CGRect leftRect; 
CGRect centerRect; 
CGRect rightRect; 
- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    leftRect = CGRectMake(-self.view.frame.size.width, SIZE_OF_SEGMENT, self.view.frame.size.width, self.view.frame.size.height-SIZE_OF_SEGMENT); 
    centerRect = CGRectMake(0, SIZE_OF_SEGMENT, self.view.frame.size.width, self.view.frame.size.height-SIZE_OF_SEGMENT); 
    rightRect = CGRectMake(self.view.frame.size.width, SIZE_OF_SEGMENT, self.view.frame.size.width, self.view.frame.size.height-SIZE_OF_SEGMENT); 

    firstView = [[UIView alloc] initWithFrame:centerRect]; 
    [firstView setBackgroundColor:[UIColor orangeColor]]; 
    secondView = [[UIView alloc] initWithFrame:rightRect]; 
    [secondView setBackgroundColor:[UIColor greenColor]]; 
    [self.view addSubview:firstView]; 
    [self.view addSubview:secondView]; 

} 

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

- (IBAction)segmentSwitch:(UISegmentedControl*)sender { 
    NSInteger selectedSegment = sender.selectedSegmentIndex; 
    [UIView beginAnimations:nil context:nil]; 
    [UIView setAnimationDuration:0.2]; 
    if (selectedSegment == 0) { 
     //toggle the correct view to be visible 
     firstView.frame = centerRect; 
     secondView.frame = rightRect; 
    } 
    else{ 
     //toggle the correct view to be visible 
     firstView.frame = leftRect; 
     secondView.frame = centerRect; 
    } 
    [UIView commitAnimations]; 
} 
@end 
1

Una rápida Versión Swift:

@IBAction func segmentControlValueChanged(_ sender: UISegmentedControl) { 

    if segmentControl.selectedSegmentIndex == 0 { 

     // do something 
    } else { 

     // do something else 
    } 
} 
Cuestiones relacionadas