【问题标题】:UISegmentedControl tintColorUISegmentedControl tintColor
【发布时间】:2015-04-26 01:08:45
【问题描述】:

我无法让 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]];
  • 是的,遗憾的是产生了相同的结果。
  • 不是最好的方法,但可能有效。尝试为UISegmentControl 的每个子视图设置颜色?

标签: ios cocoa-touch ios8 uisegmentedcontrol


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    试试这样的?

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

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

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

    UIKit User Interface Catalog

    【讨论】:

    • 解决方案是将色调颜色添加到两个级别的子视图(首先是 UISegment,然后是标签和图像视图)。所以谢谢你的想法:)
    • 奇怪的是第一次外观更改有效,但之后它就被烘烤了。哦,好吧,只会创建一个具有正确行为的类别。
    • 这个类别是个好主意,你应该在之后分享它,我猜它可能会对人们有所帮助。
    猜你喜欢
    • 1970-01-01
    • 2014-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-23
    • 2020-03-04
    • 1970-01-01
    相关资源
    最近更新 更多