问题
I have a UISegmentedControl
with 3 segments created in the storyboard
. I want to programmatically add another segment, and make the middle 2 segments the size of 1 segment. Here is an image to illustrate:
In storyboard
:

What I want to achieve programmatically:

This is what I tried:
CGFloat segmentWidth = self.segment.frame.size.width;
[self.segment insertSegmentWithTitle:@"titleName" atIndex:2 animated:NO];
[self.segment setWidth:segmentWidth / 4 forSegmentAtIndex:1];
[self.segment setWidth:segmentWidth / 4 forSegmentAtIndex:2];
[self.segment setWidth:segmentWidth / 3 forSegmentAtIndex:0];
[self.segment setWidth:segmentWidth / 3 forSegmentAtIndex:3];
It didn't give me the desirable effects. The widths were weird. How can I get the widths to be like the second image above?
回答1:
Half of 1/3 is not 1/4. It is 1/6.
You will probably want to set three of the segments and leave the last one to be set automatically to fill the remainder.
Don't run your code too early - if you do, the segmented control may not have achieved its final frame yet, so your
segmentWidth
will be wrong.
来源:https://stackoverflow.com/questions/30179886/make-2-segments-the-size-of-1-in-uisegmentedcontrol