UISegmentedControl选择了段颜色

时间:2010-02-16 03:56:46

标签: iphone colors uisegmentedcontrol

有没有办法在UISegmentedControl中自定义所选细分的颜色?

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

23 个答案:

答案 0 :(得分: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. 设置所选颜色 细分为绿色
  4. 注意:

    • 步骤1和2可以在 接口构建器,或代码为 所示。但是,步骤3只能完成 在代码中
    • 设置的颜色值 这样的符号“123.0 / 255.0”是 只是一种制作RGB值的方法 相反,标准化 UIColor要求的浮点值 (如果你愿意,可以忽略它)

答案 1 :(得分:52)

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

发件人是UISegmentedControl

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

检查它为我工作

答案 2 :(得分:22)

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

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

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

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

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

答案 3 :(得分: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 “我来帮忙”

答案 4 :(得分: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];
    }
}

答案 5 :(得分: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

答案 6 :(得分:2)

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

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

答案 7 :(得分:2)

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

mySegmentedControl.tintColor = [UIColor redColor]

答案 8 :(得分:2)

使用此:

[[UISegmentedControl appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor colorWithRed:255.0/255 green:37.0/255 blue:99.0/255 alpha:1.0]} forState:UIControlStateSelected];

答案 9 :(得分:2)

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

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

segmentControl.backgroundColor = customColor;

答案 10 :(得分:2)

为了澄清@jothikenpachi上面提供的答案,我们发现以下UISegmentController类在iOS6中运行良好,并允许在段上使用任意的开/关颜色方案。如果私有方法isSelected / setTintColor:在将来的OS版本中被更改,它将优雅地失败。关于私人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中调用此方法,这可能会导致动画闪现。要尽量减少这种情况,请尝试将“offColor”设置为IB中的UISegmentController的tintColor。

答案 11 :(得分: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];
    }    
}

答案 12 :(得分: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];
        }
    }
}

答案 13 :(得分:1)

Try this solution.    

enter image description here

enter image description here

        @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.

答案 14 :(得分:1)

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

Apple Doc ::

  

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)
}

来电: 您可以在AppDelegate

中调用此方法
  

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

答案 15 :(得分:1)

我知道这是一个古老的问题,但是现在在xcode 11 +中,您可以设置选定的细分色度enter image description here

在代码中,我们可以使用selectedSegmentTintColor。可用的iOS 13 +

答案 16 :(得分:0)

为了做你喜欢的事情,人们可能必须访问未记录的功能和黑客,这肯定会让苹果愤怒,这可能会导致你的申请被拒绝。

现在,解决方案在于使用两个按钮代替其他技巧,并在单击时更换图像。保持按钮更近,半分段控制的图像给出分段控制的错觉,这就是我建议你。

希望这有帮助。

谢谢,

Madhup

答案 17 :(得分: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];

重置未选择的索引

答案 18 :(得分: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];  

答案 19 :(得分: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]];
            }
        }
    }
}

答案 20 :(得分:0)

for l in a:
    l.reverse()

答案 21 :(得分:0)

这个Swift 4代码适合我

segmentedControl.setTitleTextAttributes([NSAttributedStringKey.foregroundColor: UIColor.red], for: .selected)

答案 22 :(得分:0)

[segmentedControl setSelectedSegmentTintColor:[UIColor darkGrayColor]];

//For iOS 13