您如何确定自定义 UINavigationItem.titleView 的大小/框架? [英] How do you determine the size/frame of a custom UINavigationItem.titleView?

查看:96
本文介绍了您如何确定自定义 UINavigationItem.titleView 的大小/框架?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

创建自定义视图并将其分配给 navigationItem.titleView 属性后,显示如下

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

自定义视图填充了两个按钮之间的空间.因此,自定义视图不会以导航栏为中心.如何在 .titleView 属性中确定视图的框架?我想在导航栏中居中一些文本,比如在时间戳下.

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.

推荐答案

如果你真的想得到 titleView 的框架(在你的顶级视图的坐标空间中),你可以这样做:

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];

如果你刚刚分配了titleView,你需要做layoutIfNeeded,因为默认情况下导航栏在下一次通过运行循环之前不会布局它的子视图.

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.

也就是说, titleView 会自动居中,如果合适的话.我认为您将自定义视图的框架(或边界)设置得过大.我测试了这两种方式:

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:

  • 我直接在 XIB 中设置了 titleView.我只是将对象库中的一个视图拖到导航栏的中心:

    它自动将视图大小调整为 128x33.调整大小手柄让我可以调整大小.它保持居中,直到与分类"按钮重叠.然后它向左移动.

  • 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.

我在 viewDidLoad 中设置了 titleView 属性:

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;
 }

结果如下:

这篇关于您如何确定自定义 UINavigationItem.titleView 的大小/框架?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆