How do I make a custom UISegmentedcontrol. I have 2 images, 1 that should be displayed when the segment is active and the other if the segment is inactive. Can i override the style or something so i have a UIsegmentedcontrol with my own images as active/inactive background?
In order to do this you must listen for the UIControlEventValueChanged and change the image yourself. You shouldn't need to subclass the UISegmentedControl - remember composition over inheritance is preferred!
I wrote this a while back for a similar problem. Maybe you can reuse some of it.
// Create a segmented control.
UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:nil];
[segmentedControl insertSegmentWithImage:[UIImage imageNamed:@"up_button.png"] atIndex:0 animated:YES];
[segmentedControl insertSegmentWithImage:[UIImage imageNamed:@"down_button.png"] atIndex:1 animated:YES];
segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar;
segmentedControl.frame = CGRectMake(0, 0, 90, 30);
[segmentedControl setMomentary:YES];
[segmentedControl addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged];
// Check if this is the first and / or the last page in order to enable or disable the back / forward button.
if ([recipesArray count] == 1) {
[segmentedControl setEnabled:NO forSegmentAtIndex:0];
[segmentedControl setEnabled:NO forSegmentAtIndex:1];
} else if ([currentIndex intValue] == 0) {
[segmentedControl setEnabled:NO forSegmentAtIndex:0];
} else if ([currentIndex intValue]+1 == [recipesArray count]) {
[segmentedControl setEnabled:NO forSegmentAtIndex:1];
}
// Initialize a bar button item with the segmented control as custom view and assign it to the right bar button item.
UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:segmentedControl];
self.navigationItem.rightBarButtonItem = barButtonItem;
[segmentedControl release];
Yes, you you DO need 2 images (on and off) for each section of the segment bar. (4 segments... 8 images.) But it lets you set a total of 16 choices! (All with only consuming 1 row in your GUI.)
I got everything working EXCEPT... how do you hide the original segment bar graphics?
Can't set alpha to 0. (It will also hide your images.)
Can't set "tintClear" to "clear". (Not sure why it makes it black and white.)
Can't set it to "hidden"... nothing will work at all.
Can't set "background" to "clear". (The background is NOT the segmentbar graphics.)
The simplest way would be to create your own control that mimics UISegmentedControl
. UISegmentedControl
just arranges a series of buttons and manages their image states for you; it doesn't do anything special.
Id much rather design,manage,alloc,position,free.... ONE segmentBar instead of 5 separate buttons.
Unfortunately, no one knows how to hide the original bar's graphics