Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a UIBarButtonItem with multiple "sections"?

I would like to create a UIBarButtonItem on my iPhone application which has two "sections". Basically I would like to have functionality equivalent to the 'Today', 'This Week', and 'All' buttons that's in the 'Most Viewed' section of the YouTube iPhone app.

It doesn't look like this functionality was accomplished with multiple UIBarButtonItems since only one of the three "sections" can be selected at a time. Does anyone know how this was done?

like image 252
Todd Avatar asked Dec 07 '25 12:12

Todd


2 Answers

What you're seeing there is a UISegmentedControl. It's pretty easy to set up. What YouTube is doing is (probably) something like this:

NSArray * items = [[NSArray alloc] initWithObjects: NSLocalizedString(@"Today", @""),
                      NSLocalizedString(@"This Week", @""),
                      NSLocalizedString(@"All", @""), nil];
UISegmentedControl * switcher = [[UISegmentedControl alloc] initWithItems: items];
[items release];

// setup the switcher: correct UI style, tint, etc.
switcher.style = UISegmentedControlStyleBar;
switcher.tint = self.navigationController.navigationBar.tintColor; // unnecessary?

// set the target function -- needs to check selectedIndex property
[switcher addTarget: self 
             action: @selector(switcherTapped:)
   forControlEvents: UIControlEventValueChanged];

// set default selection
switcher.selectedSegmentIndex = 0;

// set the switcher as a custom view to use in place of the normal title
self.navigationItem.titleView = switcher;
[switcher release];
like image 101
Jim Dovey Avatar answered Dec 10 '25 02:12

Jim Dovey


Actually, I think that he is describing a UISegmentedControl, which can be added to the navigation bar of the current view like so:

UISegmentedControl *segmentedControl = ... 
self.navigationItem.titleView = segmentedControl; 
[segmentedControl release];

You would set the segments of the UISegmentedControl ("Today, Last Week, All") like so (this also sets the callback for when the value of the control changes):

NSArray *sampleArray = --makeAnArrayHere--;
UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] 
    initWithItems:sampleArray];
[segmentedControl addTarget:self action:
    @selector(segmentAction:) forControlEvents:UIControlEventValueChanged];

I didn't copy this from a working project, so there may be some minor syntactical errors, but this should steer you in the right direction.

like image 41
mmc Avatar answered Dec 10 '25 02:12

mmc