Изменить шрифт UIBarButtonItem - PullRequest
128 голосов
/ 13 января 2012

UIToolbar with UIBarButtonItem

У меня есть UIBarButtonItem в моем UIToolbar под названием Готово . Теперь я хочу изменить шрифт со значения по умолчанию на "Trebuchet MS" с полужирным шрифтом. Как я могу это сделать?

Ответы [ 15 ]

205 голосов
/ 02 октября 2012

Если быть точным, это можно сделать, как показано ниже

[buttonItem setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys: 
    [UIFont fontWithName:@"Helvetica-Bold" size:26.0], NSFontAttributeName,
    [UIColor greenColor], NSForegroundColorAttributeName,
    nil] 
                          forState:UIControlStateNormal];

Или с буквальным синтаксисом объекта:

[buttonItem setTitleTextAttributes:@{
     NSFontAttributeName: [UIFont fontWithName:@"Helvetica-Bold" size:26.0],
     NSForegroundColorAttributeName: [UIColor greenColor]
} forState:UIControlStateNormal];

Для удобства, вот реализация Swift:

buttonItem.setTitleTextAttributes([
        NSAttributedStringKey.font: UIFont(name: "Helvetica-Bold", size: 26.0)!,
        NSAttributedStringKey.foregroundColor: UIColor.green],
    for: .normal)
124 голосов
/ 13 января 2012

Поскольку UIBarButtonItem наследует от UIBarItem, вы можете попробовать

- (void)setTitleTextAttributes:(NSDictionary *)attributes
                  forState:(UIControlState)state

, но это только для iOS5.Для iOS 3/4 вам придется использовать пользовательский вид.

119 голосов
/ 29 апреля 2013

Для тех, кто заинтересован в использовании UIAppearance для оформления шрифтов UIBarButtonItem во всем приложении, это можно сделать с помощью следующей строки кода:

Цель C:

NSDictionary *barButtonAppearanceDict = @{NSFontAttributeName : [UIFont fontWithName:@"HelveticaNeue-Light" size:12.0], NSForegroundColorAttributeName: [UIColor whiteColor]};
[[UIBarButtonItem appearance] setTitleTextAttributes:barButtonAppearanceDict forState:UIControlStateNormal];

Swift 2.3:

UIBarButtonItem.appearance().setTitleTextAttributes(
[
    NSFontAttributeName : UIFont(name: "HelveticaNeue-Light", size: 12)!,
    NSForegroundColorAttributeName : UIColor.white
],
for: .normal)

Swift 3

UIBarButtonItem.appearance().setTitleTextAttributes(
[
    NSFontAttributeName : UIFont(name: "HelveticaNeue-Light", size: 12)!,
    NSForegroundColorAttributeName : UIColor.white,
], for: .normal)

Swift 4

UIBarButtonItem.appearance().setTitleTextAttributes(
[
    NSAttributedStringKey.font : UIFont(name: "HelveticaNeue-Light", size: 12)!,
    NSAttributedStringKey.foregroundColor : UIColor.white,
], for: .normal)

Или для одного UIBarButtonItem (не для всего приложения), если у вас есть специальный шрифт для одной кнопки, в частности:

Swift 3

let barButtonItem = UIBarButton()
barButtonItem.setTitleTextAttributes([
    NSFontAttributeName : UIFont(name: "FontAwesome", size: 26)!,
    NSForegroundColorAttributeName : UIColor.white,
], for: .normal)
barButtonItem.title = "\u{f02a}"

Swift 4

let barButtonItem = UIBarButton()
barButtonItem.setTitleTextAttributes([
    NSAttributedStringKey.font : UIFont(name: "FontAwesome", size: 26)!,
    NSAttributedStringKey.foregroundColor : UIColor.white,
], for: .normal)
barButtonItem.title = "\u{f02a}"

Конечно, вы можете изменить шрифт и размер на любой, какой захотите.Я предпочитаю помещать этот код в файл AppDelegate.m в разделе didFinishLaunchingWithOptions.

Доступные атрибуты (просто добавьте их в NSDictionary):

  • NSFontAttributeName: Изменить шрифт с помощью UIFont
  • NSForegroundColorAttributeName: изменить цвет с помощью UIColor
  • NSShadow: добавить тень (см. NSShadow справочник по классам)

(Обновлено для iOS7 +)

19 голосов
/ 08 мая 2015

В Swift вы бы сделали это следующим образом:

backButtonItem.setTitleTextAttributes([
        NSFontAttributeName : UIFont(name: "Helvetica-Bold", size: 26)!,
        NSForegroundColorAttributeName : UIColor.blackColor()],
    forState: UIControlState.Normal)
16 голосов
/ 24 декабря 2013

Это отличные ответы выше. Просто обновление для iOS7:

NSDictionary *barButtonAppearanceDict = @{NSFontAttributeName : [UIFont fontWithName:@"HelveticaNeue-Thin" size:18.0] , NSForegroundColorAttributeName: [UIColor whiteColor]};
    [[UIBarButtonItem appearance] setTitleTextAttributes:barButtonAppearanceDict forState:UIControlStateNormal];
15 голосов
/ 11 августа 2015

Swift3

  buttonName.setAttributedTitle([
        NSFontAttributeName : UIFont.systemFontOfSize(18.0),
        NSForegroundColorAttributeName : UIColor.red,NSBackgroundColorAttributeName:UIColor.black],
                                     forState: UIControlState.Normal)

swift

   barbutton.setTitleTextAttributes([
        NSFontAttributeName : UIFont.systemFontOfSize(18.0),
        NSForegroundColorAttributeName : UIColor.redColor(),NSBackgroundColorAttributeName:UIColor.blackColor()],
        forState: UIControlState.Normal)

Objective-C

     [ barbutton setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
        [UIFont fontWithName:@"Helvetica-Bold" size:20.0], NSFontAttributeName,
        [UIColor redColor], NSForegroundColorAttributeName,[UIColor blackColor],NSBackgroundColorAttributeName,
        nil]
        forState:UIControlStateNormal];
7 голосов
/ 19 июня 2018

В Swift 4 вы можете изменить шрифт и цвет UIBarButtonItem, добавив следующий код.

addTodoBarButton.setTitleTextAttributes(
        [
        NSAttributedStringKey.font: UIFont(name: "HelveticaNeue-Bold", size: 17)!,
        NSAttributedStringKey.foregroundColor: UIColor.black
        ], for: .normal)
7 голосов
/ 23 октября 2013

Чтобы сделать это для некоторых UIBarButtonItems, но не для всех, я рекомендую следующий подход:

  1. Создайте UIBarButtonItem подкласс.Ничего не добавляйте к нему - вы будете использовать его только в качестве пользовательского класса в раскадровке и для его внешнего вида прокси ...
  2. В вашей раскадровке измените пользовательский класс для всех желаемых UIBarButtonItems на свойподкласс
  3. В ваш AppDelegate импортируйте ваш подкласс UIBarButtonItem и добавьте следующую строку в application:didFinishLaunchingWithOptions:

В моем случае я выделил подкласс UIBarButtonItem с единственной целью выделить текст:

[[BoldBarButtonItem appearance] setTitleTextAttributes:
  [NSDictionary dictionaryWithObjectsAndKeys: 
    [UIFont boldSystemFontOfSize:18.0], NSFontAttributeName,nil] 
                                              forState:UIControlStateNormal];
2 голосов
/ 21 апреля 2017

Свифт 3

barButtonName.setTitleTextAttributes( [NSFontAttributeName : UIFont.systemFont(ofSize: 18.0),NSForegroundColorAttributeName : UIColor.white], for: .normal) 
1 голос
/ 18 ноября 2015

В приложении:

if let font = UIFont(name: "AvenirNext-DemiBold", size: 15) {
        UIBarButtonItem.appearance().setTitleTextAttributes([NSFontAttributeName: font,NSForegroundColorAttributeName:TOOLBAR_TITLE_COLOR], forState: UIControlState.Normal)

    }
...