我可以更改我的UINavigationController的字体吗? --> 标题
我可以更改我的UINavigationController的字体吗? --> 标题
从iOS 5开始,您可以通过外观代理更改字体。
https://developer.apple.com/documentation/uikit/uiappearance
以下内容将为所有UINavigationControllers设置标题字体。
NSMutableDictionary *titleBarAttributes = [NSMutableDictionary dictionaryWithDictionary: [[UINavigationBar appearance] titleTextAttributes]];
[titleBarAttributes setValue:[UIFont fontWithName:@"Didot" size:16] forKey:NSFontAttributeName];
[[UINavigationBar appearance] setTitleTextAttributes:titleBarAttributes];
要设置返回按钮的字体,请按照以下步骤进行:
NSMutableDictionary *attributes = [NSMutableDictionary dictionaryWithDictionary: [[UIBarButtonItem appearance] titleTextAttributesForState:UIControlStateNormal]];
[attributes setValue:[UIFont fontWithName:@"Didot" size:12] forKey:NSFontAttributeName];
[[UIBarButtonItem appearance] setTitleTextAttributes:attributes forState:UIControlStateNormal];
若要设置iOS 11+中可用的大标题的字体,请执行以下操作:
if (@available(iOS 11.0, *)) {
NSMutableDictionary *largeTitleTextAttributes = [NSMutableDictionary dictionaryWithDictionary: [[UINavigationBar appearance] largeTitleTextAttributes]];
[largeTitleTextAttributes setValue:[UIFont fontWithName:@"Didot" size:32] forKey:NSFontAttributeName];
[[UINavigationBar appearance] setLargeTitleTextAttributes:largeTitleTextAttributes];
}
对于 iOS8 +,您可以使用:
[self.navigationController.navigationBar setTitleTextAttributes:@{ NSFontAttributeName: [UIFont fontWithName:@"MyFont" size:18.0f],
NSForegroundColorAttributeName: [UIColor whiteColor]
}];
快捷:
self.navigationController?.navigationBar.titleTextAttributes = [NSFontAttributeName: UIFont(name: "MyFont", size: 18.0)!]
标题视图可以是任何视图。因此,只需创建一个UILabel或其他类型的视图,在其中更改字体并将该新视图分配给导航项的标题属性。
-(void) viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
CGRect frame = CGRectMake(0, 0, 400, 44);
UILabel *label = [[[UILabel alloc] initWithFrame:frame] autorelease];
label.backgroundColor = [UIColor clearColor];
label.font = [FontHelper fontFor:FontTargetForNavigationHeadings];
label.textAlignment = UITextAlignmentCenter;
label.textColor = [UIColor whiteColor];
label.text = self.navigationItem.title;
// emboss in the same way as the native title
[label setShadowColor:[UIColor darkGrayColor]];
[label setShadowOffset:CGSizeMake(0, -0.5)];
self.navigationItem.titleView = label;
}
[UINavigationBar appearance]
无法完成任务。自定义titleView是唯一的方法。 - BabyPanda@morgancodes的答案将为所有UINavigationController
标题设置字体。我已经更新了Swift 4的代码:
let attributes = [NSAttributedStringKey.font: UIFont(name: "Menlo", size: 14) as Any]
UINavigationBar.appearance().titleTextAttributes = attributes
UIBarButtonItem.appearance().setTitleTextAttributes(attributes, for: .normal)