如何为 ios 中选定状态的分段控件中的段设置颜色

how to set color for segments in segemented control for selected state in ios

我正在使用分段控件而不是按钮。如何设置选定段的背景颜色。我正在尝试更改背景颜色,但它的颜色出现在所有片段中。

首先,创建您选择和取消选择的颜色;

UIColor *selectedColor = [UIColor blackColor];
UIColor *deselectedColor = [UIColor whiteColor];

然后,找到选定的段索引并为其着色;

for (UIControl *subview in [YourSegmentedControl subviews]) {
    if ([subview isSelected]) 
       [subview setTintColor:selectedColor]; 
    else
       [subview setTintColor:deselectedColor]; 
}

如果您设置第一个索引,则编写此代码。

[segmentControl setSelectedSegmentIndex:0];

如果设置了背景色就写这段代码

UIColor *selectedColor = [UIColor whiteColor];
   for (UIControl *subview in [segmentControl subviews]) {

        [subview setTintColor:selectedColor];

    }

如果您更改色调颜色和字体大小,请编写此代码。

NSDictionary *attributes = @{NSFontAttributeName: [UIFont boldSystemFontOfSize:12.0f]};
[segmentControl setTitleTextAttributes:attributes
                              forState:UIControlStateNormal];

[segmentControl setTitleTextAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Helvetica-Bold" size:14.0],
                                         NSForegroundColorAttributeName:[UIColor whiteColor]}
                              forState:UIControlStateNormal];
[segmentControl setTitleTextAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Helvetica-Bold" size:14.0],
                                         NSForegroundColorAttributeName:[UIColor redColor]}
                              forState:UIControlStateSelected];

我为您的 question.I 尝试了示例一,在 XIB.Also 中设置了分段控制 我设置了三个 titles.I 通过属性和操作将分段连接到 ViewController.h。

ViewController.h

#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
{
}
@property (strong, nonatomic) IBOutlet UISegmentedControl *segmentBgColorChange;
- (IBAction)actionChangeBGColor:(id)sender;
@end

ViewController.m

#import "ViewController.h"
@interface ViewController ()
{
}
@end
@implementation ViewController
@synthesize segmentBgColorChange;

// Then in action methods

- (IBAction)actionChangeBGColor:(id)sender
{
  UISegmentedControl *seg = sender;
  for (int i=0; i<[seg.subviews count]; i++) {
    if ([[seg.subviews objectAtIndex:i]isSelected]) {
        UIColor *bgColor = [UIColor redColor];
        [[seg.subviews objectAtIndex:i] setTintColor:bgColor];
    } else {
        [[seg.subviews objectAtIndex:i] setTintColor:nil];
    }
   }
 }