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

旧街凉风 提交于 2019-12-04 07:47:17

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:

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?

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