11

I'm trying to use a UISegmentedControl but having trouble calculating the width of the segments. The control makes the segments all the same width which doesn't work for some titles, like this one:

http://morrisphotoart.com/tmp/Screenshot2011-07-13_21.17.33.png

I can write code to calculate the segment width if I knew which font and call the setWidth:forSegmentAtIndex: method but how can I get the font? Or is there another way?

The left and middle segment's titles are not fixed so I can't hardcode the widths.

progrmr
  • 75,956
  • 16
  • 112
  • 147
  • You have to customize it using UILabel – stack2012 Jul 14 '11 at 04:30
  • Exactly. I could not use it for the same reason. – Nitish Jul 14 '11 at 04:30
  • I have added the code to customize it. Use that and then add it as a subview to whichever view u want. The method pickone selector does the corresponding operation for each of the segment pressed. It can be achieved by getting the segment title index value in that method. Hope this helps. – stack2012 Jul 14 '11 at 04:34
  • I have removed certain unnecessary code now – stack2012 Jul 14 '11 at 04:38

4 Answers4

30

If you can support iOS 5 and later then you can use the property apportionsSegmentWidthsByContent and set it to YES.

From the iOS 5 docs:

apportionsSegmentWidthsByContent

Indicates whether the control attempts to adjust segment widths based on their content widths.

@property(nonatomic) BOOL apportionsSegmentWidthsByContent

Discussion

If the value of this property is YES, for segments whose width value is 0, the control attempts to adjust segment widths based on their content widths.

Camsoft
  • 11,718
  • 19
  • 83
  • 120
26

EDIT: an easier option might be to use the iOS 5 property apportionsSegmentWidthsByContent as mentioned in @Camsoft's answer here


Well, I ended up getting the UIFont from poking thru the subviews (which could break in a future iOS). Being a modular/reuse aficianado, I wrote this routine to do it and then to distribute the space so that the segments in the control are evenly spaced for the titles.

-(void)resizeSegmentsToFitTitles:(UISegmentedControl*)segCtrl {
    CGFloat totalWidths = 0;    // total of all label text widths
    NSUInteger nSegments = segCtrl.subviews.count;    
    UIView* aSegment = [segCtrl.subviews objectAtIndex:0];
    UIFont* theFont = nil;

    for (UILabel* aLabel in aSegment.subviews) {
        if ([aLabel isKindOfClass:[UILabel class]]) {
            theFont = aLabel.font;
            break;
        }
    }

    // calculate width that all the title text takes up
    for (NSUInteger i=0; i < nSegments; i++) {
        CGFloat textWidth = [[segCtrl titleForSegmentAtIndex:i] sizeWithFont:theFont].width;
        totalWidths += textWidth;
    }

    // width not used up by text, its the space between labels
    CGFloat spaceWidth = segCtrl.bounds.size.width - totalWidths;   

    // now resize the segments to accomodate text size plus 
    // give them each an equal part of the leftover space
    for (NSUInteger i=0; i < nSegments; i++) {
        // size for label width plus an equal share of the space
        CGFloat textWidth = [[segCtrl titleForSegmentAtIndex:i] sizeWithFont:theFont].width;
        // roundf??  the control leaves 1 pixel gap between segments if width 
        // is not an integer value, the roundf fixes this
        CGFloat segWidth = roundf(textWidth + (spaceWidth / nSegments));    
        [segCtrl setWidth:segWidth forSegmentAtIndex:i];
    }
}
Community
  • 1
  • 1
progrmr
  • 75,956
  • 16
  • 112
  • 147
  • This is some solid code right here! I just added this method to my view controller, passed it my segmented control in my viewDidLoad method and it just took care of the rest! didn't even have to modify anything. – Christian Gossain Nov 18 '11 at 18:10
  • Except it doesn't handle the case where there is NO space left, that is where your label texts are too wide for the total width of the control, but other than minor flaw it works ;-) – progrmr Nov 19 '11 at 01:18
  • Thx progrmr! Unfortunately, this does not work any longer with iOS 7. Corrected and simplified function published [here](http://stackoverflow.com/a/23492688/2254935). – Krzysztof Przygoda May 06 '14 at 10:56
8
NSArray *itemArray = [NSArray arrayWithObjects: @"Title1", @"Title2", @"Titl3", @"Title4",nil];
segmentedControl = [[UISegmentedControl alloc] initWithItems:itemArray];
segmentedControl.frame = CGRectMake(0, 0, 310, 35);
segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar;
segmentedControl.selectedSegmentIndex = 0;
[segmentedControl addTarget:self action:@selector(pickOne:) forControlEvents:UIControlEventValueChanged];   
segmentedControl.tintColor=[UIColor grayColor];

for (id segment in [segmentedControl subviews]) 
{
    for (id label in [segment subviews]) 
    {
        if ([label isKindOfClass:[UILabel class]])
        {

            [label setTextAlignment:UITextAlignmentCenter];
            [label setFont:[UIFont boldSystemFontOfSize:12]];
        }
    }           
}
stack2012
  • 2,146
  • 2
  • 16
  • 23
  • I didn't really want to have to poke down into the subviews, but there doesn't seem to be any other way. I did get it to work by getting the font from the label subview, then I could calculate the title widths and divide up the space evenly. – progrmr Jul 14 '11 at 15:22
  • Yep. That was the best possible solution I could find when I was into the same trouble. – stack2012 Jul 15 '11 at 11:52
-1

iOS 7.1.1 friendly. We have calculate UISegmentedControl new frame size only and the rest (segments proportions) will be addressed by iOS (based on apportionsSegmentWidthsByContent).

Be aware that this doesn't work if the Auto Layout is ON.

void styleSegment_fitTitles(UISegmentedControl *segCtrl) {

    // Fit segments' titles
    [segCtrl sizeToFit];

    CGFloat em = font.pointSize;
    CGRect segCtrlRect = segCtrl.bounds;
    CGFloat segCtrlWidth = segCtrlRect.size.width + segCtrl.numberOfSegments*em;
    CGFloat segCtrlHeight = segCtrlRect.size.height + em;
    CGFloat segmentY = segCtrl.frame.origin.y - (segCtrlHeight - segCtrlRect.size.height)/2;
    segCtrl.frame = CGRectMake(segCtrl.frame.origin.x, segmentY, segCtrlWidth, segCtrlHeight);
}
Krzysztof Przygoda
  • 1,217
  • 1
  • 17
  • 24
  • CGFloat segCtrlWidth = segCtrlRect.size.width + segCtrl.numberOfSegments*em; This is not a valid way of calculating width you are just multiplying number of segments with font size. Valid way should be calculating width on basis of text in each segment – Habib Ali Feb 02 '17 at 09:12
  • @HabibAli - You're right - that's why there is an `em` unit, if you know what I mean. So, if this is somehow satisfactory to you, please rethink your downvote. – Krzysztof Przygoda May 09 '17 at 21:01
  • em = font.pointSize is not satisfactory as font size only defines height not the width of text of each segment. Got it ? – Habib Ali May 10 '17 at 07:32
  • Note that all your “magic” happens in `[segCtrl sizeToFit]` (based on `apportionsSegmentWidthsByContent`) and `em` is used here only as a padding (whitespace). – Krzysztof Przygoda May 11 '17 at 19:46