UINavigationItem#titleView 对齐问题
我发现有关使用 UINavigationItem#titleView 和自定义字体的信息很少。 当我这样做时,导航栏中的字体垂直不对齐。
这篇文章的部分目的是记录一个黑客行为,也希望有人对这个问题有一个简洁的答案,因为我觉得我错过了一些简单的东西。
首先是黑客,使用我自己的 UILabel 派生类:
@interface NavigationItemLabel : UILabel
- (void)setFrame:(CGRect)frame;
@end
@implementation NavigationItemLabel
- (void)setFrame:(CGRect)frame {
// Called by UINavigationBar layoutSubviews.
frame.origin.y -= self.font.descender;
}
@end
出于某种原因,frame.origin.y == -11,无论我使用什么字体。 有谁对这是为什么有任何直觉吗?
添加我的字体的下降部分(称为 Gabriola 的自定义字体)似乎有帮助。如果没有这个技巧,文本将与导航栏中心的下降部分的底部对齐。
这并不适用于所有字体。
有人有更好的解决方案吗?
谢谢。
I am finding little information about using UINavigationItem#titleView with a custom font.
When I have done so, the font is misaligned vertically in the navigation bar.
This entry is partly to document a hack, and also hoping someone has a succinct answer to this problem, as I feel I am missing something simple.
First the hack, using my own UILabel derived class:
@interface NavigationItemLabel : UILabel
- (void)setFrame:(CGRect)frame;
@end
@implementation NavigationItemLabel
- (void)setFrame:(CGRect)frame {
// Called by UINavigationBar layoutSubviews.
frame.origin.y -= self.font.descender;
}
@end
For some reason, frame.origin.y == -11, no matter what font I use.
Does anyone have any intuition as to why this is?
Adding my font's descender (custom font called Gabriola) seems to help. Without this hack, the text is aligned with the bottom of the descenders on the center of the navigation bar.
This doesn't work for all fonts.
Does anyone have a better solution?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您要部署到 iOS 5+,您可以查看 UINavigationBar 文档:
另外,您应该查看
titleTextAttributes
(也是 iOS5+),您可以使用它来设置自定义字体:如果您不使用 iOS5,我建议包装
UILabel 内的
UIView
并将 UIView 设置为titleView
(这允许您通过更改其frame
来进一步调整包装标签的位置)。如果您可以访问 WWDC 2012 视频(即如果您有开发者帐户),我强烈建议您观看 iOS 上的高级外观自定义(此内容包含在那里)。
希望它能有所帮助。
If you are deploying to iOS 5+, you could check out the
titleVerticalPositionAdjustmentForBarMetrics
property the in the UINavigationBar documentation:Also, you should check out
titleTextAttributes
(also iOS5+), which you can use to set a custom font:If you're NOT on iOS5, I'd suggest wrapping the
UILabel
inside aUIView
and setting your UIView astitleView
instead (this allows you to further adjust the wrapped label's position by changing itsframe
).If you have access to the WWDC 2012 videos (i.e. if you've got a developer account), I'd strongly recommend watching the talk on Advanced Appearance Customization on iOS (this stuff is included there).
Hope it helps somehow.
我在使用
Grotesque
时遇到了同样的问题,@kolyuchiy 此处展示了一个很棒的解决方案。 (它涉及下载 Apple Font Tool Suite 命令行实用程序并调整ascender 自定义字体的属性)。
I had the same problem using
Grotesque
and there was a great SO solution shown by @kolyuchiy here. (It involves downloading the Apple Font Tool Suite command line utilities and adjusting theascender
attribute for your custom font).