segmented how example control ios objective-c iphone uisegmentedcontrol

ios - how - swift 4 segmented control example



¿Cómo uso un UISegmentedControl para cambiar de vista? (10)

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

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


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


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 muestra sobre cómo se puede hacer, definitivamente no es una manera optimizada para 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.


En mi caso, mis puntos de vista son bastante complejos y no puedo simplemente cambiar la propiedad oculta de las diferentes vistas porque 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 título Vista de la barra de navegación, que no siempre muestra SegmentedControl al presionar / 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 la mejor solución que he encontrado sobre el problema hasta ahora. Con un poco de ajuste también funcionó bien con un tabBar en la parte inferior


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


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.



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).

En general, eso funciona bastante bien porque puedes diseñar la vista principal con el contenedor en IB, y las subvistas llenarán cualquier espacio que el contenedor les permita tener (asegúrate de que tus máscaras de autoresize estén configuradas correctamente).


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 hijo. La vista del controlador de vista secundaria se convierte en parte de la jerarquía de vista del controlador de vista principal.

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 infantil:

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 ControlSegurado 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 secundaria:

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 } }