Dublicate this,但它不適合我。自定義UISegmentedControl,添加背景圖片和選定的分段色調顏色
我使用UICatalog創建了UISegmentedControl並嘗試更改選定的段顏色。我用this來改變顏色。背景圖片工作正常,但不會更改選定的段顏色。我應該做些什麼修改?或者其他方法相同?我的代碼如下。
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];
}
}
}