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?
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];
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With