Change the color of selected segment control

后端 未结 4 373
离开以前
离开以前 2021-01-02 23:18

In my app,i able to change the color of the selected segment control.But the color is changed for another index rather than selected index. I can find any mistake in the ind

相关标签:
4条回答
  • I tried printing subviews of segment control on console and I detected that indexes are in reverse order, means if selectedSegment is 0 then your subview should be 2 not 0.Try printing segment control on console and you will see the same result as follows on segment action.:

    NSArray *theArr = [mSegmentedControl subviews];
                DEBUGLOG(@"controls arr: %@",theArr);
    

    Logs on console:

    controls arr: (
        "<UISegment: 0x8598ad0; frame = (77 0; 76 34); opaque = NO; layer = <CALayer: 0x8598b30>>",
        "<UISegment: 0x85986e0; frame = (0 0; 76 34); opaque = NO; layer = <CALayer: 0x8598740>>"
    )
    
    0 讨论(0)
  • 2021-01-02 23:32

    I hope you can simply change the TintColor of Segment Control. It works perfectly for me.

    0 讨论(0)
  • 2021-01-02 23:40

    check out this one

    -(IBAction)segmentBtnPressed:(UISegmentedControl*)sender{
    for (int i=0; i<[sender.subviews count]; i++) 
    {
        if ([[sender.subviews objectAtIndex:i]isSelected] ) 
        {               
        UIColor *tintcolor=[UIColor colorWithRed: 98/255.0 green:156/255.0 blue:247/255.0 alpha:1.0];
        [[sender.subviews objectAtIndex:i] setTintColor:tintcolor];
        }
        else{
         UIColor *tintcolor=[UIColor colorWithRed:127.0/255.0 green:161.0/255.0 blue:183.0/255.0 alpha:1.0];
        [[sender.subviews objectAtIndex:i] setTintColor:tintcolor];
    
        }
    }
    }
    

    Also you can check out more answers here UISegmentedControl selected segment color

    0 讨论(0)
  • 2021-01-02 23:45

    I'd recommend to create the two colors outside of your condition, makes your code a bit smaller. Then you can use a foreach to iterate over your segments :

    UIColor *selectedColor = [UIColor colorWithRed: 98/255.0 green:156/255.0 blue:247/255.0 alpha:1.0];
    UIColor *deselectedColor = [UIColor colorWithRed: 54/255.0 green:52/255.0 blue:48/255.0 alpha:1.0];
    
    for (UIControl *subview in [SegmentRound subviews]) {
        if ([subview isSelected]) 
           [subview setTintColor:selectedColor]; 
        else
           [subview setTintColor:deselectedColor]; 
    }
    
    0 讨论(0)
提交回复
热议问题