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 inacti
I had to add this extra code, in addition to having 2 different states for the "on" and "off" positions:
- (void)viewDidLoad
{
[super viewDidLoad];
// Set set segControl background to transparent
CGRect rect = CGRectMake(0, 0, 1, 1);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [[UIColor clearColor] CGColor]);
CGContextFillRect(context, rect);
UIImage *transparentImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[self.segControl setBackgroundImage:transparentImage forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
[self.segControl setDividerImage:transparentImage forLeftSegmentState:UIControlStateNormal rightSegmentState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
}
EDIT: Because this is getting some publicity, a cleaner solution is to use [UIImage new] instead of creating transparent images, as such:
[self.segControl setDividerImage:[UIImage new] forLeftSegmentState:UIControlStateNormal rightSegmentState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
[self.segControl setBackgroundImage:[UIImage new] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
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.
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.)
it works just fine
[segmentControl setImage:[UIImage imageNamed:@"Rolenew.png"] forSegmentAtIndex:0];
var transparentImage = UIGraphicsGetImageFromCurrentImageContext() as? UIImage
UIGraphicsEndImageContext()
segControl.setBackgroundImage(transparentImage, for: .normal, barMetrics: .default)
segControl.setDividerImage(transparentImage, forLeftSegmentState: .normal, rightSegmentState: .normal, barMetrics: .default)
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!