Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you determine the size/frame of a custom UINavigationItem.titleView?

After creating a custom view and assigning it to the navigationItem.titleView property it is displayed like this

enter image description here

with the custom view filling the space between the two buttons. Therefore, the custom view is not centered on the navigation bar. How do I determine the frame of the view in the .titleView property? I want to center some text in the navigation bar, say under the time stamp.

like image 738
ChrisP Avatar asked Nov 27 '11 18:11

ChrisP


2 Answers

If you really want to get titleView's frame (in your top-level view's coordinate space), you can do this:

[self.navBar layoutIfNeeded];
CGRect titleViewFrameInTopLevelViewSpace = [self.navigationItem.titleView
    convertRect:self.navigationItem.titleView.bounds
    toView:self.view];

You need to do layoutIfNeeded if you have just assigned titleView, because by default the navigation bar won't lay out its subviews until the next pass through the run loop.

That said, the titleView will be centered automatically, if it fits. I think you are setting the frame (or bounds) of your custom view too large. I tested this two ways:

  • I set up the titleView directly in the XIB. I simply dragged a View from the Object library onto the center of the navigation bar:
    XIB screen shot
    It sized the view to 128x33 automatically. The resize handles let me adjust the size. It stays centered until it overlaps the Categorize button. Then it shifts left.

  • I set the titleView property in viewDidLoad:

    - (void)viewDidLoad
    {
        [super viewDidLoad];
        UIView *customView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 50, 33)];
        customView.backgroundColor = [UIColor greenColor];
        self.navItem.titleView = customView;
     }
    

    The result looks like this:
    Simulator screen shot

like image 51
rob mayoff Avatar answered Sep 28 '22 17:09

rob mayoff


You could get the width of the leftBarButtonItem and the rightBarButtonItem after you've set them, and then use that to determine how to centre within the view you supply to titleView. That might do what you want?

like image 26
mattjgalloway Avatar answered Sep 28 '22 17:09

mattjgalloway