2011-06-08 37 views
5

我找不到有關使用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)似乎有所幫助。如果沒有這種黑客攻擊,文本將與導航欄中心的下行的底部對齊。

這不適用於所有字體。

有沒有人有更好的解決方案?

謝謝。此外

- (CGFloat)titleVerticalPositionAdjustmentForBarMetrics:(UIBarMetrics)barMetrics 
Returns the title’s vertical position adjustment for given bar metrics. 

,你應該檢查出titleTextAttributes(也iOS5的+),你可以用它來設置:

+0

一個可能的線索是Sjors Provoost有關相關問題使用sizeToFit的建議:[鏈接](http://stackoverflow.com/questions/3125245/uinavigationitem-titleview-position) – Wienke 2012-07-04 17:24:59

回答

3

如果要部署到iOS 5以上,你可以檢查出titleVerticalPositionAdjustmentForBarMetrics財產中UINavigationBar documentation自定義字體:

NSDictionary *attributes = @{ 
    UITextAttributeFont: yourFont 
}; 
[navBar setTitleTextAttributes:attributes]; 

如果你上的iOS5不,我建議包裹UILabel一個UIView內設置你用UIView代替titleView(這樣可以通過更改其frame來進一步調整包裝標籤的位置)。

如果您有權訪問WWDC 2012的視頻(即,如果您有開發者帳戶),我強烈建議您觀看Advanced Appearance Customization on iOS(此內容包含此內容)的演講。

希望它以某種方式幫助。

0

我有同樣的問題,使用Grotesque和有一個偉大的SO解決方案顯示@ kolyuchiy here。 (它涉及下載Apple Font Tool Suite命令行實用程序並調整您的自定義字體的ascender屬性)。