有什么方法可以自定义选定段的颜色UISegmentedControl
吗?
我找到了segmentedController.tintColor
属性,它可以让我自定义整个分段控件的颜色。问题是,当我为属性选择明亮的颜色时tintColor
,选定的段变得几乎无法识别(它的颜色与分段控件的其余部分几乎相同,因此很难区分选定的段和未选定的段)。所以我不能使用任何好的亮色进行分段控制。解决方案将是选定段颜色的一些单独属性,但我找不到它。有没有人解决这个问题?
有什么方法可以自定义选定段的颜色UISegmentedControl
吗?
我找到了segmentedController.tintColor
属性,它可以让我自定义整个分段控件的颜色。问题是,当我为属性选择明亮的颜色时tintColor
,选定的段变得几乎无法识别(它的颜色与分段控件的其余部分几乎相同,因此很难区分选定的段和未选定的段)。所以我不能使用任何好的亮色进行分段控制。解决方案将是选定段颜色的一些单独属性,但我找不到它。有没有人解决这个问题?
这是将所选段更改为任何 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];
此示例显示了重要步骤:
笔记:
我找到了一种在 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];
}
}
检查它为我工作
为此,您只需找到选定的段,例如通过迭代分段控件的子视图并测试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];
});
由于某种原因,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 “我是来帮忙的”
编辑:此解决方案不适用于 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];
}
}
这是我修改后的 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
用这个:
[[UISegmentedControl appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor colorWithRed:255.0/255 green:37.0/255 blue:99.0/255 alpha:1.0]} forState:UIControlStateSelected];
我使用了它,它一步改变了所有颜色。
mySegmentedControl.tintColor = [UIColor redColor]
为了澄清@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。
不确定这是否会得到应用商店的批准,但我为 UISegmentedControl 编写了一个子类,可让您设置自定义选择和未选择的颜色。查看注释以获取更多信息:
http://uihacker.blogspot.com/2010/05/iphone-uisegmentedcontrol-custom-colors.html
我刚刚在 iOS 7 上遇到了这个问题,它的工作方式与 iOS6 不同。
在 iOS 7 中,所选段的标签颜色与 UISegementControl 背景颜色相同。在 iOS 7 上更改它的唯一方法是设置 UISegmentControl 的背景颜色。
segmentControl.backgroundColor = customColor;
在段之间切换时,前两个解决方案对我不起作用。
我的解决方案是在我的视图控制器中处理段更改事件,然后在每次更改段时调用此方法:
+ (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];
}
}
我发现我可以在子视图上使用与段相同的索引的标签,以便以任何顺序对它们进行正确着色。
// 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];
}
}
}
我想知道为什么没有人提到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
您可以标记每个段,然后设置 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];
我发现上面的答案非常有帮助。我正在使用分段控件来设置旋钮的精度。我混合了上面的答案并想出了这个:
-(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];
为了做你的事情,一个人可能不得不访问未记录的功能和黑客,这肯定会让苹果大发雷霆,这可能会导致你的应用程序被拒绝。
现在,解决方案在于您使用两个按钮并在单击它们时交换它们的图像的其他技巧。保持按钮更近,半分段控制的图像给人一种分段控制的错觉,这就是我能建议你的全部。
希望这可以帮助。
谢谢,
马杜普
[segmentedControl setSelectedSegmentTintColor:[UIColor darkGrayColor]];
//For iOS 13
- (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]];
}
}
}
}
- (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];
}
}
}
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.
这个 Swift 4 代码对我有用
segmentedControl.setTitleTextAttributes([NSAttributedStringKey.foregroundColor: UIColor.red], for: .selected)