views:

1458

answers:

4

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?

A: 

What you're looking for is the UITabBar control with UITabBarItems.

Marc W
+1  A: 

Looking at the YouTube app, I think you're actually going to want to use the UISegmentedControl.

drewh
+6  A: 

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];
Jim Dovey
+2  A: 

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.

mmc