Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iphone ios7 segmented UISegmentedControl change only border color

Been looking around and trying to change just the border color (with a different text color) with no luck. Can change the tint, but changes both the text and border.

like image 553
ort11 Avatar asked Sep 27 '13 00:09

ort11


2 Answers

You can use UIAppearance proxy to set title text attributes but preserve tintColor for borders. Something like:

 [[UISegmentedControl appearance] setTitleTextAttributes:@{ 
    NSForegroundColorAttributeName : [UIColor redColor] 
 } forState:UIControlStateNormal];

Edit:

To tint images, you can use something like this in category on UImage:

- (instancetype)tintedImageWithColor:(UIColor *)tintColor {
    UIGraphicsBeginImageContextWithOptions(self.size, NO, 0.0);
    CGContextRef context = UIGraphicsGetCurrentContext();

    CGRect rect = (CGRect){ CGPointZero, self.size };
    CGContextSetBlendMode(context, kCGBlendModeNormal);
    [self drawInRect:rect];

    CGContextSetBlendMode(context, kCGBlendModeSourceIn);
    [tintColor setFill];
    CGContextFillRect(context, rect);

    UIImage *image  = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}
like image 169
kkodev Avatar answered Nov 03 '22 03:11

kkodev


I prefer different solution (no category), when you set images for UISegmentedControl than you have to alter images like that:

NSArray *items = nil;
if (NSFoundationVersionNumber>NSFoundationVersionNumber_iOS_6_1) {
  items = @[
          [[UIImage imageNamed:@"Images_Icon_Notes.png"] imageWithRenderingMode: UIImageRenderingModeAlwaysOriginal],
          [[UIImage imageNamed:@"Images_Icon_Keywords.png"] imageWithRenderingMode: UIImageRenderingModeAlwaysOriginal],
          [[UIImage imageNamed:@"Images_Icon_Actionitems.png"] imageWithRenderingMode: UIImageRenderingModeAlwaysOriginal],
          [[UIImage imageNamed:@"Images_Icon_Questions.png"] imageWithRenderingMode: UIImageRenderingModeAlwaysOriginal]
          ];
} else {
  items = @[
          [UIImage imageNamed:@"Images_Icon_Notes.png"],
          [UIImage imageNamed:@"Images_Icon_Keywords.png"],
          [UIImage imageNamed:@"Images_Icon_Actionitems.png"],
          [UIImage imageNamed:@"Images_Icon_Questions.png"]
          ];
}
UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:items];
segmentedControl.tintColor = [UIColor greenColor]; // desired color of border

Now tintColor will have impact only on border not on icons.

if provides compatibility with older iOS versions.
I must say this imageWithRenderingMode: is one of the greatest API WTF I've ever seen.

like image 43
Marek R Avatar answered Nov 03 '22 02:11

Marek R