UIToolbar Resizing causes weird UIBarButtonItem si

2019-05-25 07:51发布

问题:

When I create and add a UIToolBar and UIBarButton items, how can I get the toolbar and items to appear properly in both orientations. This is what I have so far:

self.toolbar = [[[UIToolbar alloc]initWithFrame:CGRectMake(0, 372, 320, 44)]autorelease];
self.toolbar.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;

self.deleteButton = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemTrash target:self action:@selector(deleteButtonClicked)] autorelease];
self.deleteButton.style = UIBarButtonItemStylePlain;

UIBarButtonItem *flexibleSpace = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil] autorelease];

self.shareButton = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction target:self action:@selector(shareButtonClicked)] autorelease];
self.shareButton.style = UIBarButtonItemStylePlain;
self.navigationItem.leftBarButtonItem = backItem;

NSArray *toolbarItems = [NSArray arrayWithObjects:self.shareButton,flexibleSpace,self.deleteButton,nil];
[self.toolbar setItems:toolbarItems animated:NO];   

As you can see from the images, the UIBarButtonItems look correct in portrait, but weirdly squished and off center (especially the trash icon), in landscape. Is there an obvious solution I'm missing, or do I have to do manual resizing to get this right?

It's a subtle difference, but here's what it should look like:

回答1:

You have to look at the Autoresizing option in the Size inspector both for the UIToolBar and the buttons. UIToolBar might also have a checkmark set for Autoresize subviews uncheck that so it does not influence your buttons.



回答2:

The answer, at least until iOS 5 is to use the UINavigationController's built in toolbar instead of creating your own. The built in toolbar will resize correctly and automatically.