72

有什么方法可以自定义选定段的颜色UISegmentedControl吗?

我找到了segmentedController.tintColor属性,它可以让我自定义整个分段控件的颜色。问题是,当我为属性选择明亮的颜色时tintColor,选定的段变得几乎无法识别(它的颜色与分段控件的其余部分几乎相同,因此很难区分选定的段和未选定的段)。所以我不能使用任何好的亮色进行分段控制。解决方案将是选定段颜色的一些单独属性,但我找不到它。有没有人解决这个问题?

4

23 回答 23

74

这是将所选段更改为任何 RGB 颜色的最简单方法。不需要子类化或黑客攻击。

segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar;

UIColor *newTintColor = [UIColor colorWithRed: 251/255.0 green:175/255.0 blue:93/255.0 alpha:1.0];
    segmentedControl.tintColor = newTintColor;

UIColor *newSelectedTintColor = [UIColor colorWithRed: 0/255.0 green:175/255.0 blue:0/255.0 alpha:1.0];
[[[segmentedControl subviews] objectAtIndex:0] setTintColor:newSelectedTintColor];

此示例显示了重要步骤:

  1. 将控件样式设置为“StyleBar”,这是它工作所必需的
  2. 首先将整个控件的未选择颜色设置为橙色
  3. 将选定段的颜色设置为绿色

笔记:

  • 步骤 1 和 2 可以在界面生成器中完成,也可以在代码中完成,如图所示。但是步骤 3 只能在代码中完成
  • 使用像“123.0/255.0”这样的符号设置颜色值只是一种使 RGB 值突出的方法,而不是 UIColor 所需的标准化浮点值(如果你愿意,可以忽略它)
于 2011-05-09T04:30:50.807 回答
53

我找到了一种在 UISegmentcontrol 中为选定段添加颜色的简单方法

发件人是 UISegmentControl

for (int i=0; i<[sender.subviews count]; i++) 
{
    if ([[sender.subviews objectAtIndex:i]isSelected] ) 
    {               
    UIColor *tintcolor=[UIColor colorWithRed:127.0/255.0 green:161.0/255.0 blue:183.0/255.0 alpha:1.0];
    [[sender.subviews objectAtIndex:i] setTintColor:tintcolor];
    }
   else 
    {
        [[sender.subviews objectAtIndex:i] setTintColor:nil];
    }
}

检查它为我工作

于 2012-02-08T06:40:59.667 回答
23

为此,您只需找到选定的段,例如通过迭代分段控件的子视图并测试isSelected属性,然后只需调用该setTintColor:子视图上的方法。

我通过将一个动作连接到 Interface Builder 中 ValueChanged 事件上的每个分段控件来做到这一点,我将它们连接到视图控制器文件中的这个方法,这基本上是msprague的答案:

- (IBAction)segmentedControlValueChanged:(UISegmentedControl*)sender
{
    for (int i=0; i<[sender.subviews count]; i++)
    {
        if ([[sender.subviews objectAtIndex:i] respondsToSelector:@selector(isSelected)] && [[sender.subviews objectAtIndex:i]isSelected])
        {
            [[sender.subviews objectAtIndex:i] setTintColor:[UIColor whiteColor]];
        }
        if ([[sender.subviews objectAtIndex:i] respondsToSelector:@selector(isSelected)] && ![[sender.subviews objectAtIndex:i] isSelected])
        {
            [[sender.subviews objectAtIndex:i] setTintColor:[UIColor blackColor]];
        }
    }
}

为了确保每次用户打开视图时控件都能正确显示,我还必须重写该-(void)viewDidAppear:animated方法并调用该方法,如下所示:

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    //Ensure the segmented controls are properly highlighted
    [self segmentedControlValueChanged:segmentedControlOne];
    [self segmentedControlValueChanged:segmentedControlTwo];
}

对于一些奖励积分,如果您确实想将分段控件设置为在选择时使用白色色调,那么您还需要在选择文本时将文本的颜色更改为黑色,您可以这样做:

//Create a dictionary to hold the new text attributes
NSMutableDictionary * textAttributes = [[NSMutableDictionary alloc] init];
//Add an entry to set the text to black
[textAttributes setObject:[UIColor blackColor] forKey:UITextAttributeTextColor];
//Set the attributes on the desired control but only for the selected state
[segmentedControlOne setTitleTextAttributes:textAttributes forState:UIControlStateSelected];

随着iOS 6的引入,第一次在 viewDidAppear 方法中设置所选项目的色调颜色将不起作用,为了解决这个问题,我使用大中央调度在几分之一秒后更改所选颜色,如下所示:

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.05 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
        [self segmentedControlValueChanged:segmentedControlOne];
    });
于 2012-09-24T08:02:17.267 回答
9

由于某种原因,Apple 不允许您更改标准 UISegmentedControls 的颜色。

然而,有一种“合法”的方式可以将分段控件样式更改为 UISegmentedControlStyleBar。这使它看起来略有不同,您可能不喜欢,但它确实允许颜色。

    NSArray *itemArray = [NSArray arrayWithObjects: @"One", @"Two", @"Three", nil];
UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:itemArray];

//更改栏样式和广告以查看然后释放分段控制器

segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar;
segmentedControl.tintColor = [UIColor colorWithRed:.9 green:.1 blue:.1 alpha:1]; 
[self.view addSubview:segmentedControl];
[segmentedControl release];

希望这有帮助,

Seb Kade “我是来帮忙的”

于 2010-03-30T11:38:30.730 回答
8

编辑:此解决方案不适用于 iOS 6。请参阅下面的 David Thompson 的回答。

这个线程真的很旧,但没有一个简单的答案对我有用。

只要您恢复取消选择的分段控件的颜色,接受的答案就有效。像这样的东西将在您的值更改函数中起作用:

for (int i=0; i<[control.subviews count]; i++) 
{
    if ([[control.subviews objectAtIndex:i]isSelected] ) 
    {               
        UIColor *tintcolor=[UIColor colorWithRed:127.0/255.0 green:161.0/255.0 blue:183.0/255.0 alpha:1.0];
        [[control.subviews objectAtIndex:i] setTintColor:tintcolor];
    } else {
        UIColor *tintcolor=[UIColor grayColor]; // default color
        [[control.subviews objectAtIndex:i] setTintColor:tintcolor];
    }
}
于 2012-05-25T17:29:20.300 回答
7

我知道这是一个老问题但是现在在 xcode 11 + 中,您可以设置选定的段 Tint 颜色在此处输入图像描述

在代码中我们可以使用selectedSegmentTintColor. 可用 iOS 13+

于 2019-11-21T05:30:05.010 回答
6

这是我修改后的 uihacker 的 CustomSegmentedControl 版本(见评论中的信用)。这个想法是我改变了找到应该改变 tintColor 的子视图的方法,从使用 selectedIndex 到 isSelected 方法。因为我正在使用一个自定义 UISegmentedControl,它有 3 个或更多段,子视图排序随机更改(即使 uihacker 的“hasSetSelectedIndexOnce”标志也不能解决这个问题!)。该代码仍处于早期开发阶段,因此使用它需要您自担风险。欢迎任何评论:)

此外,我添加了对界面生成器的支持,并覆盖了 setSelectedSegmentIndex 以便它也更新颜色。享受!

CustomSegmentedControl.h

//
//  CustomSegmentedControl.h
//
//  Created by Hlung on 11/22/54 BE.
//  Copyright (c) 2554 __MyCompanyName__. All rights reserved.
//
//  Credit: http://uihacker.blogspot.com/2010/05/iphone-uisegmentedcontrol-custom-colors.html

@interface CustomSegmentedControl : UISegmentedControl {
    UIColor *offColor,*onColor;
}
@property (nonatomic,retain) UIColor *offColor,*onColor;
-(id)initWithItems:(NSArray *)items offColor:(UIColor*)offcolor onColor:(UIColor*)oncolor;
@end

CustomSegmentedControl.m

#import "CustomSegmentedControl.h"

@interface CustomSegmentedControl (private)
-(void)setInitialMode;
-(void)toggleHighlightColors;
@end

@implementation CustomSegmentedControl

@synthesize offColor,onColor;

-(id)initWithItems:(NSArray *)items offColor:(UIColor*)offcolor onColor:(UIColor*)oncolor {
    if (self = [super initWithItems:items]) {
        // Initialization code
        self.offColor = offcolor;
        self.onColor = oncolor;
        [self setInitialMode];

        // default to 0, other values cause arbitrary highlighting bug
        [self setSelectedSegmentIndex:0];
    }
    return self;
}
- (void)awakeFromNib {
    // default colors
    self.offColor = [UIColor colorWithWhite:0.8 alpha:1];
    self.onColor = self.tintColor;
    [self setInitialMode];

    [self setSelectedSegmentIndex:0];
}

-(void)setInitialMode
{
    // set essential properties
    [self setBackgroundColor:[UIColor clearColor]];
    [self setSegmentedControlStyle:UISegmentedControlStyleBar];

    // loop through children and set initial tint
    for( int i = 0; i < [self.subviews count]; i++ )
    {
        [[self.subviews objectAtIndex:i] setTintColor:nil];
        [[self.subviews objectAtIndex:i] setTintColor:offColor];
    }

    // listen for updates, [self setSelectedSegmentIndex:0] triggers UIControlEventValueChanged in 5.0, 4.3 doesn't (facepalm), use  if( self.window ) to fix this
    [self addTarget:self action:@selector(toggleHighlightColors) forControlEvents:UIControlEventValueChanged];
}

// ---------------
// hlung's version
// ---------------
-(void)toggleHighlightColors
{
    // the subviews array order randomly changes all the time, change to check for "isSelected" instead
    for (id v in self.subviews) {
        if ([v isSelected]) [v setTintColor:onColor];
        else [v setTintColor:offColor];
    }
}
// override: update color when set selection
- (void)setSelectedSegmentIndex:(NSInteger)selectedSegmentIndex {
    [super setSelectedSegmentIndex:selectedSegmentIndex];
    [self toggleHighlightColors];
}
// ---------------
@end
于 2011-11-22T09:50:33.193 回答
3

用这个:

[[UISegmentedControl appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor colorWithRed:255.0/255 green:37.0/255 blue:99.0/255 alpha:1.0]} forState:UIControlStateSelected];
于 2014-09-18T06:28:42.820 回答
2

我使用了它,它一步改变了所有颜色。

mySegmentedControl.tintColor = [UIColor redColor]
于 2015-01-21T19:28:17.247 回答
2

为了澄清@jothikenpachi 上面提供的答案,我们发现以下 UISegmentController 类别在 iOS6 中运行良好,并允许对段进行任意开/关配色方案。另外,如果私有方法 isSelected/setTintColor: 在未来的操作系统版本中发生更改,它将正常失败。关于私有 API 调用等的注意事项。

@implementation UISegmentedControl(CustomTintExtension) {
-(void) updateCustomTintColorOn:(UIColor*)onColor Off:(UIColor*)offColor {
// Convenience function to rest the tint colors after selection, called upon change of selected index

SEL tint = @selector(setTintColor:);

for (UIView *view in [self subviews]) {
    // Loop through the views...
    if (view && ([view respondsToSelector:tint])) {
        [view performSelector:tint withObject:nil];
    }
    if (view && ([view respondsToSelector:tint])) {
        [view performSelector:tint withObject:offColor];
    }
}

// Checking if segment subview is selected...
SEL isSelected = @selector(isSelected);
for (UIView *view in [self subviews]) {
    if ([view respondsToSelector:isSelected] && [view performSelector:isSelected withObject:nil])
    {
        [view performSelector:tint withObject:onColor];
        break;
    }
}

}

请注意,此类别方法将从 UISegmentController 的- (IBAction) segmentAction: (id)sender方法中调用。

另请注意,对于 iOS6,您可能需要最初在管理 UIViewController 中调用此方法,- (void)viewDidAppear:(BOOL)animated这可能会导致动画闪烁。为了尽量减少这种情况,请尝试在 IB 中将“offColor”设置为 UISegmentController 的 tintColor。

于 2012-10-02T03:59:27.283 回答
2

不确定这是否会得到应用商店的批准,但我为 UISegmentedControl 编写了一个子类,可让您设置自定义选择和未选择的颜色。查看注释以获取更多信息:

http://uihacker.blogspot.com/2010/05/iphone-uisegmentedcontrol-custom-colors.html

于 2010-05-27T23:30:08.467 回答
2

我刚刚在 iOS 7 上遇到了这个问题,它的工作方式与 iOS6 不同。

在 iOS 7 中,所选段的标签颜色与 UISegementControl 背景颜色相同。在 iOS 7 上更改它的唯一方法是设置 UISegmentControl 的背景颜色。

segmentControl.backgroundColor = customColor;
于 2014-01-06T21:52:32.870 回答
1

在段之间切换时,前两个解决方案对我不起作用。

我的解决方案是在我的视图控制器中处理段更改事件,然后在每次更改段时调用此方法:

+ (void)setSegmentedControl:(UISegmentedControl *)segmentedControl 
              selectedColor:(UIColor *)selectedColor 
            deselectedColor:(UIColor *)deselectedColor
{
    for (int i = 0; i < segmentedControl.subviews.count; i++) 
    {
        id subView = [segmentedControl.subviews objectAtIndex:i];

        if ([subView isSelected])
            [subView setTintColor:selectedColor];
        else
            [subView setTintColor:deselectedColor];
    }    
}
于 2012-07-27T20:07:55.443 回答
1

我发现我可以在子视图上使用与段相同的索引的标签,以便以任何顺序对它们进行正确着色。

// In viewWillAppear set up the segmented control 

// then for 3 segments:  
self.navigationItem.titleView = segmentedControl;
//Order of subviews can change randomly!, so Tag them with same index as segment
[[[segmentedControl subviews]objectAtIndex:0]setTag:0]; 
[[[segmentedControl subviews]objectAtIndex:1]setTag:1];
[[[segmentedControl subviews]objectAtIndex:2]setTag:2];


// color follows the selected segment
- (IBAction)mySelector:(id)sender {
selector = [sender selectedSegmentIndex]
  for (id seg in [segmentedControl subviews]) {
    for (id label in [seg subviews]) {
        if ([seg tag] == selector){
            [seg setTintColor:selectedColor];
        } else {
            [seg setTintColor:nonSelectedColor];
        }
    }
  }
}

// in viewDidAppear for returning to the view
[segmentedControl setSelectedSegmentIndex:selector];
for (id seg in [segmentedControl subviews]) {
    for (id label in [seg subviews]) {
        if ([seg tag] == selector){
            [seg setTintColor:selectedColor];
        } else {
            [seg setTintColor:nonSelectedColor];
        }
    }
}
于 2012-03-05T02:47:51.190 回答
1

我想知道为什么没有人提到UIAppearanceProxy

苹果文档::

https://developer.apple.com/documentation/uikit/uisegmentedcontrol#1653545

示例代码:

    private class func applyUISegmentControlAppearance(){
    let apperance = UISegmentedControl.appearance()

    // Set Navigation bar Title colour
    let unselAttrib = [NSForegroundColorAttributeName:UIColor.yellow,
                                        NSFontAttributeName: UIFont.systemFont(ofSize: 15)]

    let selAttrib = [NSForegroundColorAttributeName:UIColor.red,
                     NSFontAttributeName: UIFont.boldSystemFont(ofSize: 15)]


    apperance.setTitleTextAttributes(unselAttrib, for: .normal)
    apperance.setTitleTextAttributes(selAttrib, for: .selected)
}

Call From:AppDelegate你可以在from 中调用这个方法

application(_ application: UIApplication, willFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool

于 2018-03-01T15:47:08.110 回答
0

您可以标记每个段,然后设置 TintColor forTag:

#define kTagOffState 0
#define kTagOnState  2

#define UIColorFromRGB(rgbValue) [UIColor \
        colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 \
        green:((float)((rgbValue & 0xFF00) >> 8))/255.0 \
        blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]

//usage     UIColor color = UIColorFromRGB(0xF7F7F7);

 UIColor onColor = UIColorFromRGB(0xF7F7F7);
 UIColor offColor = UIColorFromRGB(0x878787);

        [multiStateControl setTag:kTagOffState forSegmentAtIndex:0];
        [multiStateControl setTag:kTagOnState forSegmentAtIndex:1];
        [multiStateControl setTintColor:onColor forTag:kTagOnState];
        [multiStateControl setTintColor:offColor forTag:kTagOffState];  
于 2012-02-28T18:09:45.637 回答
0

我发现上面的答案非常有帮助。我正在使用分段控件来设置旋钮的精度。我混合了上面的答案并想出了这个:

-(void) viewDidLoad {

NSArray *segments = [NSArray arrayWithObjects:@"Course", @"Fine",nil];

[knob setPrecision:0.1]; // initial precision
// Set starting values

UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:segments];

segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar;
segmentedControl.frame = CGRectMake(120, 680, 228, 30);
[segmentedControl addTarget:self action:@selector(precisionSelect:) forControlEvents:UIControlEventValueChanged];
segmentedControl.momentary = YES;

[self.view addSubview:segmentedControl];
}   

- (void)precisionSelect:(UISegmentedControl*)sender
{   
    UIColor *tintcolor = [UIColor darkGrayColor];   
    if (sender.selectedSegmentIndex == 0) {
        [[sender.subviews objectAtIndex:0] setTintColor:nil];
        [[sender.subviews objectAtIndex:1] setTintColor:tintcolor];
    [knob setPrecision:0.1]; // Coarse
    } else {
        [[sender.subviews objectAtIndex:0] setTintColor:tintcolor];
        [[sender.subviews objectAtIndex:1] setTintColor:nil];
    [knob setPrecision:0.05]; // Fine
    }

}

希望这对其他人有所帮助。对我来说,一个关键是能够使用以下方法重置未选择的索引:setTintColor:nil];

于 2012-08-11T11:47:50.810 回答
0

为了做你的事情,一个人可能不得不访问未记录的功能和黑客,这肯定会让苹果大发雷霆,这可能会导致你的应用程序被拒绝。

现在,解决方案在于您使用两个按钮并在单击它们时交换它们的图像的其他技巧。保持按钮更近,半分段控制的图像给人一种分段控制的错觉,这就是我能建议你的全部。

希望这可以帮助。

谢谢,

马杜普

于 2010-02-16T04:25:22.770 回答
0
[segmentedControl setSelectedSegmentTintColor:[UIColor darkGrayColor]];

//For iOS 13
于 2019-09-27T15:30:54.350 回答
0
- (IBAction)segmentControlValueChanged:(UISegmentedControl *)sender
{
    if ([[sender.subviews firstObject] respondsToSelector:@selector(setTintColor:)]) {
        for (id segment in sender.subviews) {
            if ([segment respondsToSelector:@selector(isSelected)] && [segment isSelected]) {
                [segment setTintColor:[UIColor redColor]];
            } else {
                [segment setTintColor:[UIColor grayColor]];
            }
        }
    }
}
于 2015-08-18T10:25:11.290 回答
0
- (IBAction)segmentedControlValueChanged:(UISegmentedControl *)sender {
    for (int i = 0; i < sender.subviews.count; i++) {
        UIControl *component = [sender.subviews objectAtIndex:i];
        if ([component respondsToSelector:@selector(isSelected)]) {
            UIColor *selectedColor = [UIColor greenColor];
            UIColor *normalColor   = [UIColor blackColor];
            UIColor *tint = component.isSelected ? selectedColor : normalColor;
            [component setTintColor:tint];
        }
    }
}
于 2016-08-24T07:47:47.600 回答
0
Try this solution.    

在此处输入图像描述

在此处输入图像描述

        @IBAction func dashBoardSegmentValueChanged(sender: AnyObject) {
            switch dashBoardSegment.selectedSegmentIndex
            {
            case 0:     
                sender.subviews.last?.backgroundColor = UIColor.whiteColor()
                sender.subviews.first?.backgroundColor =  UIColor.clearColor()

                break;
            case 1:            
                sender.subviews.first?.backgroundColor =  UIColor.whiteColor()
                sender.subviews.last?.backgroundColor = UIColor.clearColor()
                break;
            default:
                break;
            }
        }

Note: Make sure you select one segment subview as initial selected for easiness. It works if you have two segment subviews.
于 2016-01-06T05:40:48.240 回答
-1

这个 Swift 4 代码对我有用

segmentedControl.setTitleTextAttributes([NSAttributedStringKey.foregroundColor: UIColor.red], for: .selected)
于 2018-06-06T14:29:18.970 回答