Customizing the colors of a UISegmentedControl

nicktmro picture nicktmro · Jul 28, 2009 · Viewed 51.8k times · Source

Does anybody know of a way to customize the appearance of the string based UISegmentedControl? I am trying to set the background color of the cell and the text color differently depending on the selected state of the item.

Alternatively, do you know of a way to create UIImages on the fly in which to include custom strings? (e.g. create UUImage with white background, overlay text, add to segmented control).

I know that you can only have strings or images in the segmented control...

Answer

Arclite picture Arclite · Jul 29, 2009

UISegmentedControl has a tintColor property -- this allows you to change what color the control is, but not the general "style" (the rounded, beveled shape):

segmentedControl.tintColor = [UIColor blueColor];

As for creating UIImages on the fly, you can create a CGContext, do whatever drawing you need to in that context (including strings), and then get a UIImage out of the context's CGImage:

CGContextRef drawContext = CGBitmapContextCreate(<many parameters>);
//do drawing here
CGImageRef finalImage = CGBitmapContextCreateImage(drawContext);
UIImage *cellImage = [UIImage finalImage];

Please note, that if you use code like UIView.appearance().tintColor = .myColor (or equiv. in ObjC), the effect most likely won't take place.