更改UINavigationController标题的字体

时间:2010-10-30 16:44:32

标签: ios fonts uinavigationcontroller title

我可以更改UINavigationController的字体吗? - > 标题

5 个答案:

答案 0 :(得分:72)

从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];
}

答案 1 :(得分:22)

对于iOS8 +,您可以使用:

prod = db.query("select * from sources.product 
where post = '310551835'"

夫特:

[self.navigationController.navigationBar setTitleTextAttributes:@{ NSFontAttributeName: [UIFont fontWithName:@"MyFont" size:18.0f],
                                                                   NSForegroundColorAttributeName: [UIColor whiteColor]
                                                                   }];

答案 2 :(得分:13)

标题视图可以是任何视图。因此,只需创建一个UILabel或其他更改字体的位置,并将该新视图分配给导航项的title属性。

答案 3 :(得分:10)

一个例子:

-(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;
}

答案 4 :(得分:1)

@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)