这是此问题的副本,但对我没有用。
我使用UICatalog创建了UISegmentedControl并尝试更改选定段的颜色。 我使用此代码来更改颜色。 背景图像很好地工作,但它不会更改所选段的颜色。 我需要做哪些修改? 或者有其他解决方案吗? 下面是我的代码。
NSArray *segmentTextContent = @[@"First",@"Second",@"Third"];
UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:segmentTextContent];
segmentedControl.frame = CGRectMake(20, 50, 280, 30);
[segmentedControl addTarget:self
action:@selector(segmentAction:)
forControlEvents:UIControlEventValueChanged];
segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar;
segmentedControl.selectedSegmentIndex = 1;
segmentedControl.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;
[segmentedControl setBackgroundImage:[UIImage imageNamed:@"navigationBar"]
forState:UIControlStateNormal
barMetrics:UIBarMetricsDefault];
[segmentedControl setDividerImage:[UIImage imageNamed:@"divider"]
forLeftSegmentState:UIControlStateNormal
rightSegmentState:UIControlStateNormal
barMetrics:UIBarMetricsDefault];
// we want attributed strings for this segmented control
NSDictionary *textAttributes = @{ UITextAttributeTextColor:[UIColor whiteColor],
UITextAttributeFont:[UIFont fontWithName:@"HelveticaNeue-Bold" size:13] };
[segmentedControl setTitleTextAttributes:textAttributes forState:UIControlStateNormal];
textAttributes = @{ UITextAttributeTextColor:[UIColor whiteColor],
UITextAttributeFont:[UIFont fontWithName:@"HelveticaNeue-Bold" size:13] };
[segmentedControl setTitleTextAttributes:textAttributes forState:UIControlStateHighlighted];
[self.view addSubview:segmentedControl];
- (void)segmentAction:(UISegmentedControl *)sender
{
for (int i=0; i<[sender.subviews count]; i++) {
if ([[sender.subviews objectAtIndex:i]isSelected]) {
UIColor *tintcolor = [UIColor greenColor];
[[sender.subviews objectAtIndex:i] setTintColor:tintcolor];
} else {
[[sender.subviews objectAtIndex:i] setTintColor:nil];
}
}
}