Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UISegmentedControl tintColor

I'm having problems getting UISegmentedControl to show the desired tint color.

// AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // need red tint color in other views of the app
    [[UIView appearance] setTintColor:[UIColor redColor]];
    return YES;
}

// ViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    NSArray *items = @[@"Item 1", @"Item 2"];
    UISegmentedControl *control = [[UISegmentedControl alloc] initWithItems:items];
    // would like to have this control to have a green tint color
    control.tintColor = [UIColor greenColor];
    [self.view addSubview:control];
}

How to make UISegmentedControl use the green tint color?

like image 725
Miha Hribar Avatar asked Apr 25 '15 15:04

Miha Hribar


Video Answer


2 Answers

I ended up creating a category for the desired behaviour. Subview structure looks like this:

UISegment
   UISegmentLabel
   UIImageView
UISegment
   UISegmentLabel
   UIImageView

So two loops are required for the desired effect (otherwise some parts stay in old tint color).

UISegmentedControl+TintColor.h

#import <UIKit/UIKit.h>

@interface UISegmentedControl (TintColor)

@end

UISegmentedControl+TintColor.m

#import "UISegmentedControl+TintColor.h"

@implementation UISegmentedControl (TintColor)

- (void)setTintColor:(UIColor *)tintColor {
    [super setTintColor:tintColor];
    for (UIView *subview in self.subviews) {
        subview.tintColor = tintColor;
        for (UIView *subsubview in subview.subviews) {
            subsubview.tintColor = tintColor;
        }
    }
}

@end
like image 186
Miha Hribar Avatar answered Sep 28 '22 06:09

Miha Hribar


Try something like this ?

for (UIView *subView in mySegmentedControl.subviews)
{
   [subView setTintColor: [UIColor greenColor]];
}

But it actually appears that it is a known issue in iOS 7, I don't know if it has been fixed in iOS 8.

"You cannot customize the segmented control’s style on iOS 7. Segmented controls only have one style"

UIKit User Interface Catalog

like image 26
BoilingLime Avatar answered Sep 28 '22 06:09

BoilingLime