How do I get the width of the back button in a UINavigationBar?

Deadly 提交于 2019-12-03 04:06:36

You could always spelunk through the navigation bar's subviews, looking for the back button view and picking off the size when you find it. I did a blog post a while back on iterating through subviews of a UIView, here is the URL:

http://www.dosomethinghere.com/2011/07/09/logging-the-view-hierarchy/

I am using the InspectView class described in the above URL in my current app, and when I inserted this code into a view controller that has a back button in the navigation bar:

- (void)viewDidAppear:(BOOL)animated
{
    [InspectView dumpViewToLog:self.navigationController.navigationBar findParent:NO];
}

This is the resulting output in the console:

2011-09-20 09:11:19.599 MyApp[2070:207] 
Inspect view hierarchy -----------------------------------
UINavigationBar (0x6626460): frame origin: (0, 20) size: (320, 44) [tag=0] UIView : UIResponder : NSObject : 
.   UILabel (0x6613f00): frame origin: (62, 0) size: (200, 44) [tag=0] UIView : UIResponder : NSObject : 
.   .   UILabel (0x6628520): frame origin: (0, 19) size: (200, 20) [tag=0] UIView : UIResponder : NSObject : 
.   .   UILabel (0x665eda0): frame origin: (0, -1) size: (200, 24) [tag=0] UIView : UIResponder : NSObject : 
.   UINavigationItemButtonView (0x662a5b0): frame origin: (5, 7) size: (49, 30) [tag=0] UINavigationItemView : UIView : UIResponder : NSObject : 
End of view hierarchy -----------------------------------

The UINavigationItemButtonView is the back button, and you can see that the size if 49 wide by 30 tall. You would look for this view class in your app and remember the size.

Please keep in mind that putting this code into viewDidLoad or viewWillAppear will show different results.

try this way

  NSLog(@"frame =%f",self.navigationController.navigationItem.rightBarButtonItem.width);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!