如何在UISegmentedcontrol中更改选定和未选定的段的颜色?

时间:2016-01-12 13:46:12

标签: ios objective-c uisegmentedcontrol

I want the UISegmentedcontrol like this

我想更改所选和未选定的细分色彩。 任何人都可以帮助我吗?

2 个答案:

答案 0 :(得分:1)

尝试这样的事情

self.segmantControl.backgroundColor = [UIColor colorWithRed:114.0/255. green:197./255. blue:182./255. alpha:1.0];

//如果你在IB / storyboard中没有约束,你应该以编程方式设置高度约束

NSLayoutConstraint *constraint = [NSLayoutConstraint constraintWithItem:self.segmantControl
                                                              attribute:NSLayoutAttributeHeight
                                                              relatedBy:NSLayoutRelationEqual
                                                                 toItem:nil
                                                              attribute:NSLayoutAttributeWidth
                                                             multiplier:1
                                                               constant:55];
[self.segmantControl addConstraint:constraint];

//如果你在IB / storyboard中有约束,你应该使用name(segmentHeight)将属性设置为高度约束

self.segmentHeight.constant = 55; // height constraint, U should add constraints to your segment control and set property to height constraint, and change it
self.segmantControl.layer.cornerRadius = 25.0;
self.segmantControl.layer.borderColor = [UIColor whiteColor].CGColor;
self.segmantControl.layer.borderWidth = 1.0f;
self.segmantControl.layer.masksToBounds = YES;

// color selected text ---> whiteColor
[[UISegmentedControl appearance] setTitleTextAttributes:@{ NSForegroundColorAttributeName : [UIColor whiteColor] } forState:UIControlStateSelected];
// color disabled text ---> whiteColor
[[UISegmentedControl appearance] setTitleTextAttributes:@{ NSForegroundColorAttributeName : [UIColor whiteColor] } forState:UIControlStateNormal];

UIColor *newSelectedTintColor = [UIColor colorWithRed:109./255. green:175./255. blue:179./255 alpha:1.0];
[[[self.segmantControl subviews] objectAtIndex:0] setTintColor:newSelectedTintColor];//selected left segment color
[[[self.segmantControl subviews] objectAtIndex:1] setTintColor:newSelectedTintColor];// selected right segment colour

结果: enter image description here

答案 1 :(得分:0)

试试这个

self.segmentedControl.tintColor = [UIColour greenColor];

点击任何细分后,更改所选细分的颜色:

- (void)selectedSegment:(UISegmentedControl *)sender
{
    for (int i=0; i<[sender.subviews count]; i++) 
{
        if ([[sender.subviews objectAtIndex:i]isSelected]) 
{
    UIColor *tintcolor = [UIColor blueColor];
    [[sender.subviews objectAtIndex:i] setTintColor:tintcolor];
}
 else 
{
            [[sender.subviews objectAtIndex:i] setTintColor:nil];
        }
    }
}