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?
For iOS 11 (and maybe above) the call:
will return a zero point origin for the view. To counter this, ask for the window coordinates of the view, by using:
If your toolbar has any translations subtract them from the calculated point to find its position on the toolbar.
Complete Code:
I used this which seems to be the most elegant way
A more 'swifty' SWIFT way:
UIBarButtonItem is NOT a subclass of UIView even though it's essentially a button. Go figure.
I used johosher's approach to get the position of a UIBarButtonItem using Swift.
Since I needed the position as sourceRect for a popoverPresentationController I had to convert it to self.view. I am not sure, whether this is a good solution but it works very well and the popover shows off right of the UIBarButtonItem.
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:
This works for me when using popovers from UIBarButtonItems.