Alex Rivera | Logout

How to determine position of UIBarButtonItem in UIToolbar?

Asked 2011-11-22T18:21:50.297
13

What's the easiest way to determine the x,y location of a UIBarButtonItem in a UIToolbar?

The only answer I found is in any way to know where uibarbuttonitem has been drawn.

All proposed answers seem too complicated. There ought to be a simpler way to get the position of the damn UIBarButtonItem isn't there?

Edit
Report

1 Answer

12

Unfortunately, there is no easy way of determining the position of a UIBarButtonItem. A UIBarButtonItem is essentially a NSObject that does just two things: describe the look and feel of a toolbar button, and forward events to the designated target/action selector.

Now, given that all buttons are subviews of UIToolbar, and all button events are routed through their respective UIBarButtonItems, it's quite trivial to loop through all subviews of your UIToolbar and when you find a button whose target is that of your UIBarButtonItem, just get the frame of that button. Some code:

UIToolbar *toolbar = <your toolbar>;
UIBarButtonItem *barButtonItem = <your item>;
UIButton *button = nil;
for (UIView *subview in toolbar.subviews) {
    if ([subview isKindOfClass:[UIButton class]]) {
        for (id target in [(UIButton *)subview allTargets]) {
            if (target == barButtonItem) {
                button = (UIButton *)subview;
                break;
            }
        }
        if (button != nil) break;
    }
}
CGRect frame = button.frame;
answered 2011-11-25T21:36:33.650

Your Answer