【发布时间】:2011-05-02 20:37:03
【问题描述】:
我可以更改 UINavigationController 的字体吗? --> 标题
【问题讨论】:
标签: ios fonts uinavigationcontroller title
我可以更改 UINavigationController 的字体吗? --> 标题
【问题讨论】:
标签: ios fonts uinavigationcontroller title
标题视图可以是任何视图。因此,只需创建一个 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 是唯一的方法。
从 iOS 5 开始,您可以通过外观代理更改字体。
https://developer.apple.com/documentation/uikit/uiappearance
以下将为所有 UINavigationController 设置标题字体。
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)!]
【讨论】:
来自@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)
【讨论】: