Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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:

enter image description here

What I want to achieve programmatically:

enter image description here

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
260 views
Welcome To Ask or Share your Answers For Others

1 Answer

  1. Half of 1/3 is not 1/4. It is 1/6.

  2. You will probably want to set three of the segments and leave the last one to be set automatically to fill the remainder.

  3. 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...