更改NavigationItem的字体

Ank*_*yas 19 iphone

我用这段代码来改变一个NavigationItem标题:

self.navigationItem.title = @"My Name is ABC";
Run Code Online (Sandbox Code Playgroud)

如何更改字体大小和字体?

Mih*_*hta 32

示例代码:

CGRect frame = CGRectMake(0, 0, 400, 44);
UILabel *label = [[[UILabel alloc] initWithFrame:frame] autorelease];
label.backgroundColor = [UIColor clearColor];
label.font = [UIFont boldSystemFontOfSize:8.0];
label.textAlignment = UITextAlignmentCenter;
label.textColor = [UIColor whiteColor];
label.text = @"Sample custom Title With small Fonts ";
self.navigationItem.titleView = label;
Run Code Online (Sandbox Code Playgroud)


Sne*_*ess 18

从iOS5 +开始,您可以使用UIAppearance协议来更改导航标题的字体,这里是代码:

NSMutableDictionary *titleBarAttributes = [NSMutableDictionary dictionaryWithDictionary: [[UINavigationBar appearance] titleTextAttributes]];
[titleBarAttributes setValue:[UIFont fontWithName:@"Helvetica-Bold" size:18] forKey:UITextAttributeFont];
[[UINavigationBar appearance] setTitleTextAttributes:titleBarAttributes];
Run Code Online (Sandbox Code Playgroud)


Bra*_*das 10

从iOS5开始,您可以titleTextAttributes像这样使用新属性:

NSMutableDictionary *newAttributes = [[NSMutableDictionary alloc] init]; 
[newAttributes setObject:[UIFont boldSystemFontOfSize:18] forKey:UITextAttributeFont];
[self.navigationController.navigationBar setTitleTextAttributes:newAttributes];
Run Code Online (Sandbox Code Playgroud)

可能的关键是:

UITextAttributeFont
UITextAttributeTextColor
UITextAttributeTextShadowColor
UITextAttributeTextShadowOffset
Run Code Online (Sandbox Code Playgroud)


CGu*_*ess 6

要使上面的示例居中,您必须使文本的大小只与文本一样宽,这应该可以解决问题

UIFont * font = [UIFont fontWithName:@"Helvetica" size:18.0f];
CGRect frame = CGRectMake(0, 0, [@"Lorem Ipsum" sizeWithFont:font].width, 44);
Run Code Online (Sandbox Code Playgroud)