UISegmentedControl tintColor

时间:2015-04-25 15:57:07

标签: ios cocoa-touch ios8 uisegmentedcontrol

我在使UISegmentedControl显示所需的色调时遇到问题。

// 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];
}

如何使UISegmentedControl使用绿色色调?

2 个答案:

答案 0 :(得分:7)

我最终为所需行为创建了一个类别。子视图结构如下所示:

UISegment
   UISegmentLabel
   UIImageView
UISegment
   UISegmentLabel
   UIImageView

因此,所需效果需要两个循环(否则某些部分保持旧色调)。

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

答案 1 :(得分:3)

尝试这样的事情?

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

但实际上它似乎是iOS 7中的已知问题,我不知道它是否已在iOS 8中修复。

&#34;您无法在iOS 7上自定义分段控件的样式。分段控件只有一种样式&#34;

UIKit User Interface Catalog