如何确定自定义 UINavigationItem.titleView 的大小/框架?
创建自定义视图并将其分配给 navigationItem.titleView 属性后,它的显示方式如下
>视图填充两个按钮之间的空间。因此,自定义视图并不以导航栏为中心。如何确定 .titleView 属性中视图的框架?我想在导航栏中居中放置一些文本,例如在时间戳下方。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您确实想获取
titleView
的框架(在顶级视图的坐标空间中),您可以这样做:如果您刚刚分配了,则需要执行
layoutIfNeeded
titleView
,因为默认情况下导航栏不会布置其子视图,直到下一次通过运行循环。也就是说,
titleView
将自动居中(如果合适)。我认为您将自定义视图的框架(或边界)设置得太大。我通过两种方式进行了测试:我直接在 XIB 中设置
titleView
。我只是将一个视图从对象库拖到导航栏的中心:它自动将视图大小调整为 128x33。调整大小手柄让我可以调整大小。它保持居中状态,直到与“分类”按钮重叠。然后它向左移动。
我在
viewDidLoad
中设置了titleView
属性:结果如下所示:
If you really want to get
titleView
's frame (in your top-level view's coordinate space), you can do this:You need to do
layoutIfNeeded
if you have just assignedtitleView
, 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 inviewDidLoad
:The result looks like this:
您可以在设置
leftBarButtonItem
和rightBarButtonItem
后获取它们的宽度,然后使用它来确定如何在您提供给的视图中居中标题视图
。这可能会达到你想要的效果吗?You could get the width of the
leftBarButtonItem
and therightBarButtonItem
after you've set them, and then use that to determine how to centre within the view you supply totitleView
. That might do what you want?