Pergunta

Eu estou tentando descobrir como usar os diferentes estados de um UISegmentedControl para vistas de switch, semelhante à forma como a Apple faz na App Store quando switiching entre 'Top Paid' e 'Top Free'.

Foi útil?

Solução

A abordagem mais simples é ter dois pontos de vista que você pode alternar a sua visibilidade para indicar qual a vista foi selecionado. Aqui está um código de exemplo de como isso pode ser feito, definitivamente não é uma forma otimizada para lidar com os pontos de vista, mas apenas para demonstrar como você pode usar o UISegmentControl para alternar a visualização visível:

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


Pode, claro, mais re-fator o código para ocultar / mostrar a vista direita.

Outras dicas

No meu caso meus pontos de vista são bastante complexas e não posso simplesmente alterar a propriedade oculta de diferentes pontos de vista, porque levaria muita memória.

Eu tentei várias soluções e não deles trabalhou para mim, ou executada de forma irregular, especialmente com o titleView do navBar nem sempre mostrando o segmentedControl ao empurrar / popping vistas.

Eu encontrei este post sobre o assunto que explica como fazê-lo da maneira adequada. Parece que ele teve a ajuda de engenheiros da Apple em WWDC'2010 para chegar a esta solução.

http://redartisan.com/2010/6/ 27 / uisegmented-controlo-vista de comutação-Revisited

A solução neste ligação é de longe a melhor solução que eu encontrei sobre o assunto até agora. Com um pouco de ajuste também funcionou bem com uma barra de páginas na parte inferior

Ou se a sua mesa, você pode recarregar a tabela e em cellForRowAtIndex, preencher a tabela a partir de diferentes fontes de dados com base na opção segmento selecionado.

Uma idéia é ter a visão com os controles segmentados têm uma visão recipiente que você preencher com as diferentes subviews (adicionar como um único subexibição da visão recipiente quando os segmentos são alternados). Você pode até ter controladores de vista separados para essas subviews, mas você tem de transmitir em métodos importantes como "viewWillAppear" e "viewWillDisappear" se você precisar deles (e eles terão de ser dito o controlador de navegação estão sob).

Geralmente isso funciona muito bem porque você pode colocar para fora da vista principal com o recipiente em IB, e os subviews irá preencher o espaço que o recipiente permite que eles têm (Verifique se o seu máscaras AutoResize estão configurados corretamente).

Tente este código, isso ajuda você a alternar entre diferentes pontos de vista sobre mudança segmentos de controlo de segmentos

Abertas diferentes visões sobre selecionando diferentes segmentos da UISegmentControl

Tente usar SNFSegmentedViewController , um componente de código aberto que faz exatamente o que você está procurando com um configuração como UITabBarController.

A partir da resposta de @Ronnie Liew, eu criar esta:

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

Atribuir .H no

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

Versão Swift:

O controlador de vista pai é responsável por definir o tamanho e posição da vista de cada controlador de vista da criança. A visão do controlador de vista criança torna-se parte da hierarquia de vista o ponto de vista do controlador pai.

Definir propriedades preguiçosos:

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 Criança de Visualização de Controladores:

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

Gerenciar SegmentedControl tapEvent

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

E, claro, você é capaz de usar dentro de suas classes do controlador da Criança:

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

Referência: https://cocoacasts.com/managing-view-controllers-with -container-view-controladores /

Uma rápida Swift Versão:

@IBAction func segmentControlValueChanged(_ sender: UISegmentedControl) {

    if segmentControl.selectedSegmentIndex == 0 {

        // do something
    } else {

        // do something else
    }
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top