Automatic resizing in the navigation pane of a segmented control built dynamically

The controller adds a UISegmentedControl to the navigation bar. Segmented control is added to the navigation bar in the controller's viewDidLoad method, but the actual segments are created dynamically after calling viewDidLoad .

I cannot automatically resize segments when displaying a view. They all flatten out, as in this message , although the resolution does not apply here. If segments are added before the segmented control is added to the right element of the navigation panel (disrupting the dynamic nature of the code), they automatically change and look great when the view is displayed.

Here is 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 
+6
source share
2 answers

After calling invoke insertSegmentWithTitle

[segmentedControl sizeToFit];

+14
source

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

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

 [segmentedControl setNeedsLayout]; 
+1
source

Source: https://habr.com/ru/post/896304/


All Articles