6

A controller adds a UISegmentedControl to a navigation bar. The segmented control is added to the navigation bar in the viewDidLoad method of the controller but the actual segments are created dynamically after viewDidLoad is called.

I can't get the segments to be resized automatically when the view is shown. They are all squished, like in this post, though the resolution doesn't apply here. If the segments are added before the segmented control is added to the right item of the navigation bar (breaking the dynamic nature of the code), they are resized automatically and look fine when the view is shown.

Here's a stripped down version of my code, below. What am I missing?

@implementation MyController    

- (void)viewDidLoad {

    // segmentedControl is an ivar
    segmentedControl = [UISegmentedControl alloc] initWithItems:[NSArray array]];
    UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:segmentedControl] autorelease];
    self.navigationController.navigationBar.topItem.rightBarButtonItem = barButtonItem;

}

- (void)someMethodCalledAfterViewDidLoad {

    [segmentedControl insertSegmentWithTitle:@"a title"
                                     atIndex:0
                                    animated:NO];
}

@end
Community
  • 1
  • 1
ptrico
  • 1,049
  • 7
  • 22

2 Answers2

14

After calling insertSegmentWithTitle call

[segmentedControl sizeToFit];

Krzysztof Luks
  • 290
  • 2
  • 8
1

I had the same problem today - the UISegmentedControl segments were initially displayed with the proper variable widths, but did not expand or contract to fit the length of new, dynamically updated titles.

Sending the segmented control a setNeedsLayout message after each update solved the problem.

[segmentedControl setNeedsLayout];
fedonev
  • 20,327
  • 2
  • 25
  • 34
  • Hi @fedonev, thanks for answering this old question. I'll accept your answer though I haven't tested it myself. I think I ended up calculating and setting the width on each segment programmatically. Your solution sounds simpler. – ptrico Jan 09 '12 at 10:19
  • sizeToFit does the job, and in cases where the segment titles have been changed. – Jeff Oct 28 '12 at 22:57