3

How can I use UISegmentedControl to load different subviews when different segments are selected? Im new to objective-c and iOS programming.

OR is there a way to make UITabBarController look like a UISegmentedControl?

Jessy
  • 31
  • 1
  • 2

4 Answers4

3

For a programatic approach

in loadView:

{
    NSArray *segments = [NSArray arrayWithObjects:@"Left", @"Right", nil];


    segmentedControl = [[UISegmentedControl alloc]initWithItems:segments];
    [segmentedControl addTarget:self
    action:@selector(changeSubViews)
    forControlEvents:UIControlEventValueChanged];
    contentView = [UIView alloc]initwithFrame:(the frame where you want the subViews to be displayed)];
    [self.view addSubView:contentView];

    }

    - (void)changeSubViews
        {
            switch(segmentedControl.selectedSegmentIndex)
            {
            case 0:
                {
                    [rightView removeFromSuperView];
                    if (leftView ==nil){leftView alloc, init;}
                    [contentView addSubView:leftView];
                    break;
                }
            case 1:
                {
                    [leftView removeFromSuperView];
                    if (rightView ==nil){rightView alloc, init;}
                    [contentView addSubView:rightView];
                    break;
                }
            }
    }
Tim
  • 41,901
  • 18
  • 127
  • 145
1

You could add a UIToolbar to your root controller's view. In it, you'd have a UISegementedControl with actions that the root controller handle. Depending on the segment clicked, you would load up a different view and display the view under the UIToolbar (and anything else that you want the view to be below).

Hope this helps!

donkim
  • 13,119
  • 3
  • 42
  • 47
0

Ok for this purpose you make two views in your view and make property for both in .h file and Attach an IBAction to the segmented control and write code like this

if(self.yourSegmentedControl.selectedSegmentIndex==0)
    {   
    view1.hidden=YES;
        view2.hidden=NO;
    }
    else if(self.categorySegmentedControl.selectedSegmentIndex==1)
    {  
    view2.hidden=YES;
        view2.hidden=NO:
    }

Hope this will help you.

Vivek Sehrawat
  • 6,560
  • 2
  • 26
  • 39
Ishu
  • 12,797
  • 5
  • 35
  • 51
  • I already know how to do this. But how do I show the active subview while hiding inactive subviews? just like the tabbar – Jessy Dec 24 '10 at 05:07
  • why not you make two view where you use same segmented control.And you can show selection of the segment control. – Ishu Dec 24 '10 at 05:12
  • that's my question. I don't know how to do that – Jessy Dec 24 '10 at 05:14
0

You should consider crafterm's answer in this post: UISegmentedControl Best Practice

This will allow you to maintain your normal ViewController behavior (support rotation, memory warnings, etc.) while allowing for the segmented control on top of it.

Community
  • 1
  • 1
Ohad Kravchick
  • 1,154
  • 11
  • 15