UISegmentedControl tintColor

5

我在使用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 使用绿色调色板?


你尝试过这个吗:[[UISegmentedControl appearance] setTintColor:[UIColor greenColor]]; - BoilingLime
是的,遗憾地产生了相同的结果。 - Miha Hribar
1
这不是最好的方法,但可能有效。尝试为UISegmentControl的每个子视图设置颜色? - BoilingLime
2个回答

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

3
尝试类似以下的内容吗?
for (UIView *subView in mySegmentedControl.subviews)
{
   [subView setTintColor: [UIColor greenColor]];
}

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

“您无法在iOS 7上自定义分段控件的样式。分段控件只有一种样式”

UIKit用户界面目录


解决方案是将色调颜色添加到两个子视图级别(第一个是UISegment,然后它有一个标签和一个ImageView)。所以感谢这个想法 :) - Miha Hribar
第一次外观更改奏效很奇怪,但之后就被固定了。好吧,我会创建一个具有正确行为的类别。 - Miha Hribar
这个分类是个好主意,你应该分享一下,这可能会帮助到其他人。 - BoilingLime

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接