开发者

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

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜