I'm trying to figure out a clean way to make a UIToolbar
only as wide as it needs to be to fit the items that it contains. Is there a way to either:
UIToolbar
to adjust its width automatically as its items are changed?UIToolbar
's frame?I haven't been able to figure this out due to the spacing between the items and the fact that UIBarButtonItem
s are not UIView
subclasses.
After trying some suggestions from other answers that did not work unless I used custom views, or unless everything was loaded, I finally arrived at a way to set the toolbar width based on its items:
//Add bar items to toolbar first.
UIView* v = toolbar.subviews.lastObject;
float newWidth = v.frame.origin.x + v.frame.size.width;
//Set toolbar width
You'll need to override UIToolbar -setItems:
or otherwise detect changed buttons to autoresize.
I have included this feature in my refactoring library, es_ios_utils, to set a navigation item's right item with multiple buttons. In the preceding link, see UIToolbar +toolbarWithItems:
and UINavigationItem -setRightBarButtonItems
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With