Good UISegmentedControl example

Dec 26, 2011   //   by admin   //   iOS  //  1 Comment

I initially referred to the article below, but when I implemented it, I found it too cumbersome

http://idevrecipes.com/2010/12/13/wooduinavigation/

So here is a much simpler method:

Here is the .h file:

#import <UIKit/UIKit.h>

@interface NewsViewController : UIViewController
{

IBOutlet UITableView *myTableView;
UISegmentedControl *segmentedControl;
NewsType oldType;

…etc
}

@property (nonatomic, retain) UITableView *myTableView;
@property (nonatomic, retain, readonly) IBOutlet UISegmentedControl * segmentedControl;
- (void)didChangeSegmentControl:(UISegmentedControl *)control;

@end

Here is the *.m file:

In this function:

1. We initialise the Segmented Control.
2. Add the target selector function didChangeSegmentControl.
3. Set the size of the button.
4. Set the control style.
5. Set the initial selected index.

- (void)viewDidLoad
{

// Need to do all this initialisation before calling base classes
segmentedControl = [[UISegmentedControl alloc] initWithItems: [NSArray arrayWithObjects: @"Tab 1", @"Tab 2", @"Tab 3", nil]]; // 1

[segmentedControl addTarget:self action:@selector(didChangeSegmentControl:) forControlEvents:UIControlEventValueChanged]; // 2
segmentedControl.frame = CGRectMake(0, 0, 220, 30); // 3
segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar; // 4
segmentedControl.selectedSegmentIndex = 0; // 5

}

This function is then called when the button is clicked with the new index, in this function we take the appropriate action.

- (void)didChangeSegmentControl:(UISegmentedControl *)control
{
// To get string: [control titleForSegmentAtIndex:control.selectedSegmentIndex]
if (control.selectedSegmentIndex == 0)
{
newsType = NEWSFEED;
}
else if (control.selectedSegmentIndex == 1)
{
newsType = NEWSFEED;
}
else if (control.selectedSegmentIndex == 2)
{
newsType = FACEBOOK;
}
Update your data according and refresh your table
[myTableView reloadData];
}

And that is it, using the standard iPhone buttons.

If you need any help with your Mobile app, or have a requirement to develop a mobile app, The App Experience develop mobile apps on multiple platforms (iOS, Android, Symbian, Windows Mobile), please get in contact here

 

1 Comment

  • Really good knowledge! I have been searching for everything like that for quite a while now. Thanks!

Leave a comment