Search code examples
iosswiftuiimageframeuitabbaritem

iOS - Getting frame of the UIImageView/UIImage of a UITabBarItem


I am trying to get the frame of an image shown in a UITaBarItem. I can get the view of any UITabBarItem but can't able to get the frame of only image part of any UITabBarItem. Adding an screenshot of my views enter image description here


Solution

  • For getting UIBarButtonItem's view

    public extension UIBarButtonItem {
    
        var view: UIView? {
            guard let view = self.value(forKey: "view") as? UIView else {
                return nil
            }
            return view
        }
    }
    

    For getting UIImageView from UIBarButtonItem view:

    let barItemImageView = self.navigationItem.rightBarButtonItem?.view.subviews.filter { view in
            view is UIImageView
            }.first
    

    This will return the UIImageView of my right UIBarButtonItem