开发者

Automatic resizing in a navigation bar of a segmented control built dynamically

开发者 https://www.devze.com 2023-04-01 09:54 出处:网络
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 dynamic

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开发者_JAVA技巧 = [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


After calling insertSegmentWithTitle call

[segmentedControl sizeToFit];


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];
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号