开发者

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

开发者 https://www.devze.com 2023-04-06 16:25 出处:网络
We have a controller that might be pushed from several places, so its back button might have one of several titles.It also has a button that pops up another controller.They both have the same custom t

We have a controller that might be pushed from several places, so its back button might have one of several titles. It also has a button that pops up another controller. They both have the same custom title element, but they're centred differently because the second controller 开发者_StackOverflow社区has no back button. I'd like to add a spacer to fix this, but I don't know what width to make it. How do I get the width of the back button in a UINavigationBar?


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);
0

精彩评论

暂无评论...
验证码 换一张
取 消