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

Deadly 提交于 2019-12-12 08:53:46

问题


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

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.


回答1:


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:


    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:




回答2:


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?



来源:https://stackoverflow.com/questions/8287894/how-do-you-determine-the-size-frame-of-a-custom-uinavigationitem-titleview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!