开发者

UISegmentedControl not centered on UINavigationController when added programmatically

开发者 https://www.devze.com 2023-02-05 17:04 出处:网络
I\'m using the following code in my root view controller class implementation: - (void)viewDidLoad { [super viewDidLoad];

I'm using the following code in my root view controller class implementation:

- (void)viewDidLoad 
{
    [super viewDidLoad];

    NSArray *segmentTextContent = [NSArray arrayWithObjects:
                                   NSLocalizedString(@"button1", @""),
                                   NSLocalizedString(@"button2", @""),
                                   NSLocalizedString(@"button3", @""), nil];

    UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] nitWithItems:segmentTextContent];
    segmentedControl.selectedSegmentIndex = 0;
    segmentedControl.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar;
    segmentedControl.frame = CGRectMake(0, 0, 400, 30);

    self.navigationItem.titleView = segmentedControl;
    [segmentedControl release];
}

The segmented control is not centered correctly, it is shifted a few pixels to the right. The funny thing is, it is not right-aligned either. It's as if there is some left padding preventing it from being centered. Another funny thing is, if I draw this segmented control in interface builder, it centers perfectly, so this is only a programmatic issue.

I've tried this code in a brand new empty app and get the same results, so I know it's not something else in my app that开发者_如何学编程 is causing it.

Sorry, I wanted to post a screen shot, but I don't have enough reputation points ;-)

Any Ideas?


There is no left button, I've even tried doing:

self.navigationItem.leftBarButtonItem = nil;
self.navigationItem.backBarButtonItem = nil;

As I said, it works in IB, just not in code. And it also fails in a brand new project - you can try it for yourself, and see...

I seemed to have found the fix. The 400 specified for the width was causing the problem. I specified 300, and now it is centered correctly. I supposed ideally I should be grabbing some global screen width value instead of hard-coding 300.

0

精彩评论

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