Change textColor in UISegmentedcontrol

2019-04-17 09:25发布

问题:

I use below code for change textcolor of each segmented in UISegmentedcontrol how can I change textcolor of specific segment?(for example segment at index 2)

for (id seg in [segment subviews]) 
     for (id label in [seg subviews]) 
        if ([label isKindOfClass:[UILabel class]])
                [label setTextColor:[UIColor redColor]];

回答1:

i use below code for this problem

int eg=0;
    for (id seg in [sg subviews]) 
    {
        int gg=sg.selectedSegmentIndex;
        if(gg==2)
            gg=0;
        else if(gg==0)
            gg=2;
        if(eg==gg && eg!=1)
        {
            for (id label in [seg subviews]) 
                if ([label isKindOfClass:[UILabel class]])
                {
                    [label setTextAlignment:UITextAlignmentCenter];
                    [label setFont:[UIFont boldSystemFontOfSize:12]];
                    [label setTextColor:[UIColor colorWithRed:0.325 green:0.565 blue:0.788 alpha:1]];
                }//if
        }//if
        else if(eg==1)
        {
            for (id label in [seg subviews]) 
                if ([label isKindOfClass:[UILabel class]])
                {
                    [label setTextAlignment:UITextAlignmentCenter];
                    [label setFont:[UIFont boldSystemFontOfSize:11]];
                    [label setTextColor:[UIColor grayColor]];   
                }//if
        }//else if
        else
        {
            for (id label in [seg subviews]) 
                if ([label isKindOfClass:[UILabel class]])
                {
                    [label setTextAlignment:UITextAlignmentCenter];
                    [label setFont:[UIFont boldSystemFontOfSize:11]];
                    [label setTextColor:[UIColor colorWithRed:0.888 green:0.888 blue:0.888 alpha:1]];   
                }//if
        }//else
        eg++;
    }//for


回答2:

As far as I know there is no customization-based solution for this. But you can either use images for necessary segments (setImage:forSegmentAtIndex:) or look at this: http://matteocaldari.it/2010/05/a-uisegmentedcontrol-with-custom-color (authors have subclassed UISegmentedControl & implemented custom drawing in overriden drawRect: method).