UISegmentedControl with square corners

21.5k Views Asked by At

I would like to modify UISegmentedControl with a subclass to remove the rounded corners. I can't seem to set the cornerRadius. Making the SegmentedControl wider than the screen (and therefor "chop" off the corners) is not an option since I have 4 or 5 segments and they would then vary in size.

Is there a way to do this?

Thanks

5

There are 5 best solutions below

3
On BEST ANSWER

You can set the width of the segments (using setWidth:forSegmentAtIndex:) so you can easily make the left and right end segments larger (say 10px larger) than the others and then you can crop off 10px from either end and have square corners. You don't have to make it larger than the screen width, instead put it inside a UIView and use it to crop the ends.

On the other hand just could just make your own segmented control using a set of custom UIButtons inside a UIControl.

2
On

One alternative, if "cropping" part of the first and last segment is problematic, may be to crop the entire first and last segment (which you've made dummy unused segments). That way you can still keep a common size for every segment.

3
On

To make the corner square use the following code:

segmentContrl.layer.borderColor=*anycolor*.CGColor;
segmentContrl.layer.cornerRadius = 0.0;
segmentContrl.layer.borderWidth = 1.5f;
1
On

Just use the built in customization methods and set a background image for each segment state. This will override the border entirely. If the background images are square, then your segmented control will appear square. Use the following code for each segment state you want to customize.

[segmentedControl setBackgroundImage:[UIImage imageNamed:@"square-background-image-selected"] forState:UIControlStateSelected barMetrics:UIBarMetricsDefault];

2
On

Another alternative to accomplish this in interface builder:

Drag a UIView object to your UIViewController, this may be a subview of your UIView.

Drag a UISegmentedControl as a subview of your UIView. The segmented control should now be indented in your list UIViewController objects. (see screenshot below).

Resize the SegementedControl so that its' frame is outside the boundaries of your UIView object. In my case I set the frame of the SegementedControl to X = -10 and added +20 to the width of the SegementedControl so that the total width of the segmented control because 20 greater then the UIView object. (hopefully, the screen shot below helps).

I also adjusted the following settings for the UIView object and SegmentedControl: UIView: check Clip SubViews, uncheck AutoResize Subviews. SegementedControl: uncheck Clip SubViews, uncheck AutoResize Subviews.

enter image description here