Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine position of UIBarButtonItem in UIToolbar?

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?

like image 216
Hisham Avatar asked Nov 22 '11 18:11

Hisham


1 Answers

For iOS 11 (and maybe above) the call:

if let view = barButtonItemView.value(forKey: "view") as? UIView {
        let viewFrame = view.frame    
}

will return a zero point origin for the view. To counter this, ask for the window coordinates of the view, by using:

let actualPointOnWindow = view.convert(view.frame.origin, to: nil)

If your toolbar has any translations subtract them from the calculated point to find its position on the toolbar.

Complete Code:

if let view = barButtonItemView.value(forKey: "view") as? UIView {
     let viewFrame = view.frame    
     let actualPointOnWindow = view.convert(view.frame.origin, to: nil)
}
like image 131
Don Miguel Avatar answered Oct 26 '22 01:10

Don Miguel