Lalit_vicky
Lalit_vicky

Reputation: 295

Unable to highlight the segment control properly ios

I am using a segment control and when its unselected and user tries to move to next screen , then it should get highlighted.

My code logic:

+(void) validateSegmentControl:(UISegmentedControl *) segmentControl
{
    // mark invalid field
    segmentControl.layer.cornerRadius=4.0f;
    segmentControl.layer.masksToBounds=YES;
    segmentControl.layer.borderColor=[UIColor colorWithRed:175/255.0 green:14/255.0 blue:37/255.0 alpha:1].CGColor;
    segmentControl.layer.borderWidth=1.0f;
}

But the problem is , the red highlight is little out of the segment control. Not sure why it's happening .tried reducing the corner radius but no luck.

here is the image: enter image description here

What could be the problem.

Upvotes: 1

Views: 207

Answers (2)

Balram Tiwari
Balram Tiwari

Reputation: 5667

The best option is to not to set the width of the segmentedControl manually. You just init the segmented control with Items like

UISegmentedControl * yourSegmentControl  = [[UISegmentedControl alloc]initWithItems:@[@"All", @"Due", @"OverDue", @"Cleared"]];
[yourSegmentControl sizeToFit];

this way the segments are automatically adjusted for width depending upon number of elements, leaving you to not to worry about custom width. This is efficient code as well.

This way, the layer of your component is also well aligned to the actual border.

hope that helps.

Upvotes: 0

Xu Yin
Xu Yin

Reputation: 3940

I found out that, if you divided the width of your segmented controller by the number of your segments, if that returns an integer, all your codes work fine, on the other hand, if that returns a value with decimal places, you will end up the way you have now. For example:

if my segmented controller have 4 segments, and it's total width 240. 240/4 = 60, it's an integer value. After adding border, it looks like this:

enter image description here

but when i change the width to 250, 250/4 = 62.5, which has decimal places, it becomes like this:

enter image description here

So i think in your case, the easiest solution would be simply change the width of your segmented control to X, which X = (segment width) * 3, and segment width has to be an integer value.

Hope that helps. and to be honest, i never knew that before this question. And i can't explain why, seems like the SDK renders the segmented control that way.

Upvotes: 2

Related Questions