Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Size a UIToolbar to fit its items?

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:

  • Configure the UIToolbar to adjust its width automatically as its items are changed?
  • Programatically determine the minimum width required by the items, which can then be used to set the UIToolbar's frame?

I haven't been able to figure this out due to the spacing between the items and the fact that UIBarButtonItems are not UIView subclasses.

like image 620
Bryan Irace Avatar asked Nov 06 '22 03:11

Bryan Irace


1 Answers

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.

like image 200
Peter DeWeese Avatar answered Nov 12 '22 19:11

Peter DeWeese