开发者

Size a UIToolbar to fit its items?

开发者 https://www.devze.com 2023-02-09 06:35 出处:网络
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 t开发者_如何学Gohat it contains. Is there a way to either:

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 t开发者_如何学Gohat 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.


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.


I just checked the documentation and seems like UIBarButtonItems, even though they are not UIView subclasses, they have an attribute width. I didn't try it myself, but I think you could sum each item's width, including the flexible item, and get the width for your toolbar. Hope it helps! ;)


Swift 3, 4 update

I have a toolbar with barButtonItem initiated with image. All I need to do is to calculate the total width of the images plus the intervals (margin.)

Margin is by default 11 in width. The code will be:

let width: CGFloat = YourBarButtonItemList.reduce(0) {sofar, new in
    if let image = new.image {
        return sofar + image.size.width + 11
    } else {
        return sofar + ADefaultValueIfThisDoesntWork + 11
    }
}
0

精彩评论

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

关注公众号