Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the frame of UIBarButtonItem in Swift?

how could I get the frame of a rightbarbuttonItem in swift? I found this : UIBarButtonItem: How can I find its frame? but it says cannot convert NSString to UIView, or cannot convert NSString to String :

let str : NSString = "view" //or type String
let theView : UIView = self.navigationItem.rightBarButtonItem!.valueForKey("view")//or 'str'

The goal is to remove the rightBarButtonItem, add an imageView instead, and move it with a fadeOut effect.

Thanks

like image 753
Paul Avatar asked Mar 11 '15 15:03

Paul


2 Answers

You should try it like:

var barButtonItem = self.navigationItem.rightBarButtonItem!
var buttonItemView = barButtonItem.valueForKey("view")

var buttonItemSize = buttonItemView?.size

Edit (Swift 3):

var barButtonItem = self.navigationItem.rightBarButtonItem!
let buttonItemView = barButtonItem.value(forKey: "view") as? UIView
var buttonItemSize = buttonItemView?.size
like image 145
Christian Avatar answered Nov 05 '22 15:11

Christian


In Swift4, XCode9

    for view in (self.navigationController?.navigationBar.subviews)! {
        if let findClass = NSClassFromString("_UINavigationBarContentView") {
            if view.isKind(of: findClass) {
                if let barView = self.navigationItem.rightBarButtonItem?.value(forKey: "view") as? UIView {
                    let barFrame = barView.frame
                    let rect = barView.convert(barFrame, to: view)
                }
            }
        }
    }
like image 41
ePing Tu Avatar answered Nov 05 '22 14:11

ePing Tu