Pregunta

Estoy tratando de descubrir cómo usar los diferentes estados de un control UISegmentedControl para cambiar de vista, de forma similar a como lo hace Apple en la App Store al cambiar entre 'Top Paid' y 'Top Free'.

¿Fue útil?

Solución

El enfoque más simple es tener dos vistas en las que puede alternar su visibilidad para indicar qué vista ha sido seleccionada. Aquí hay un código de muestra sobre cómo se puede hacer, definitivamente no es una forma optimizada de manejar las vistas, sino solo para demostrar cómo puede usar 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.

Otros consejos

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

He probado varias soluciones y ninguna de ellas funcionó para mí, o funcionó de manera errática, especialmente con el titleView de la barra de navegación que no siempre muestra el control segmentado al presionar / hacer estallar las vistas.

Encontré esta publicación de blog sobre el problema que explica cómo hacerlo de la manera adecuada. Parece que contó con 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 problema hasta ahora. Con un poco de ajuste, también funcionó bien con una barra de pestañas en la parte inferior

O si se trata de una tabla, puede volver a cargar la tabla y, en cellForRowAtIndex, llenar la tabla desde diferentes fuentes de datos según la opción de segmento seleccionada.

Una idea es hacer que la vista con los controles segmentados tenga una vista de contenedor que usted complete con las diferentes subvistas (agregue 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 & Quot; viewWillAppear & Quot; y " viewWillDisappear " si los necesita (y se les deberá informar en qué controlador de navegación se encuentran).

En general, eso funciona bastante bien porque puede diseñar la vista principal con el contenedor en IB, y las subvistas llenarán cualquier espacio que el contenedor les permita (asegúrese de que sus máscaras de tamaño automático estén configuradas correctamente).

Pruebe este código, esto le ayudará a cambiar entre diferentes vistas al cambiar segmentos de Segment COntrol

Abra diferentes vistas al seleccionar diferentes segmentos de UISegmentControl

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

A partir 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

Asignar .H en

 UISegmentedControl *lblSegChange;

- (IBAction)segValChange:(UISegmentedControl *) sender

Declarar .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];
 }
} 

Versión Swift:

El controlador de vista principal es responsable de establecer el tamaño y la posición de la vista de cada controlador de vista secundario. La vista del controlador de vista hijo se convierte en parte de la jerarquía de vistas del controlador de vista padre.

Definir propiedades perezosas:

private lazy var summaryViewController: SummaryViewController = {
   // Load Storyboard
   let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main)

   // Instantiate View Controller
   var viewController = storyboard.instantiateViewController(withIdentifier: "SummaryViewController") as! SummaryViewController

   // Add View Controller as Child View Controller
   self.add(asChildViewController: viewController)

   return viewController
}()

private lazy var sessionsViewController: SessionsViewController = {
    // Load Storyboard
    let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main)

    // Instantiate View Controller
    var viewController = storyboard.instantiateViewController(withIdentifier: "SessionsViewController") as! SessionsViewController

    // Add View Controller as Child View Controller
    self.add(asChildViewController: viewController)

    return viewController
}()

Mostrar / Ocultar controladores de vista secundarios:

private func add(asChildViewController viewController: UIViewController) {
    // Add Child View Controller
    addChildViewController(viewController)

    // Add Child View as Subview
    view.addSubview(viewController.view)

    // Configure Child View
    viewController.view.frame = view.bounds
    viewController.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]

    // Notify Child View Controller
    viewController.didMove(toParentViewController: self)
}

private func remove(asChildViewController viewController: UIViewController) {
    // Notify Child View Controller
    viewController.willMove(toParentViewController: nil)

    // Remove Child View From Superview
    viewController.view.removeFromSuperview()

    // Notify Child View Controller
    viewController.removeFromParentViewController()
}

Administrar SegmentedControl tapEvent

private func updateView() {
    if segmentedControl.selectedSegmentIndex == 0 {
        remove(asChildViewController: sessionsViewController)
        add(asChildViewController: summaryViewController)
    } else {
        remove(asChildViewController: summaryViewController)
        add(asChildViewController: sessionsViewController)
    }
}

Y, por supuesto, puede usar dentro de sus clases de controlador de vista hijo:

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    print("Summary View Controller Will Appear")
}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    print("Summary View Controller Will Disappear")
}

Referencia: https://cocoacasts.com/managing-view-controllers-with -container-view-controllers /

Una versión rápida de Swift:

@IBAction func segmentControlValueChanged(_ sender: UISegmentedControl) {

    if segmentControl.selectedSegmentIndex == 0 {

        // do something
    } else {

        // do something else
    }
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top