Подтвердить что ты не робот

Изменить шрифт UIBarButtonItem

UIToolbar with UIBarButtonItem

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

4b9b3361

Ответ 1

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

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

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

Ответ 2

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

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

Ответ 3

Для тех, кто заинтересован в использовании UIAppearance для 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)

Свифт 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 (не для всего приложения), если у вас есть собственный шрифт для одной кнопки, в частности:

Свифт 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 класс NSShadow)

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

Ответ 4

В Swift вы выполните следующее:

backButtonItem.setTitleTextAttributes([
        NSFontAttributeName : UIFont(name: "Helvetica-Bold", size: 26)!,
        NSForegroundColorAttributeName : UIColor.blackColor()],
    forState: UIControlState.Normal)

Ответ 5

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

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

Ответ 6

Swift3

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

скор

   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

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

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

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

[[BoldBarButtonItem appearance] setTitleTextAttributes:
  [NSDictionary dictionaryWithObjectsAndKeys: 
    [UIFont boldSystemFontOfSize:18.0], NSFontAttributeName,nil] 
                                              forState:UIControlStateNormal];

Ответ 8

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

addTodoBarButton.setTitleTextAttributes(
        [
        NSAttributedStringKey.font: UIFont(name: "HelveticaNeue-Bold", size: 17)!,
        NSAttributedStringKey.foregroundColor: UIColor.black
        ], for: .normal)

Ответ 9

swift 3

barButtonName.setTitleTextAttributes( [NSFontAttributeName : UIFont.systemFont(ofSize: 18.0),NSForegroundColorAttributeName : UIColor.white], for: .normal) 

Ответ 10

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

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

    }

Ответ 11

UIBarButton не имеют свойства, связанные с изменением шрифта. Но вы можете создать кнопку с пользовательским шрифтом, а затем добавить в UIBarButton. Это может решить вашу проблему.

Ответ 12

Предполагая, что вы хотите поддерживать iOS4 и более ранние версии, лучше всего создать кнопку бара с помощью метода initWithCustomView: и предоставить свой собственный вид, который может быть чем-то вроде UIButton, где вы можете легко настроить шрифт.

Вы также можете перетащить UIButton на панель инструментов или панель навигации в Interface Builder, если вы хотите создать кнопку с перетаскиванием вместо программного.

К сожалению, это означает создание фонового изображения кнопки самостоятельно. Нет способа настроить шрифт стандартного UIBarButtonItem до iOS5.

Ответ 13

Вы можете создать пользовательский UIView программно:

UIView *buttonItemView = [[UIView alloc] initWithFrame:buttonFrame];

Затем добавьте изображения, ярлыки или все, что вам нравится, в пользовательский вид:

[buttonItemView addSubview:customImage];

[buttonItemView addSubview:customLabel];

...

Теперь поставьте его в свой UIBarButtomItem.

UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:buttonItemView];

И, наконец, добавьте barButtonItem в панель навигации.

Ответ 14

Это правильный путь: объявите ваш barButtonItem (в данном случае rightBarButtonItem) и добавьте его setTitleTextAttributes.

navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Go!", style: .plain, target: self, action: #selector(yourFuncDestination))

после того, как вы можете добавить атрибуты заголовка

navigationItem.rightBarButtonItem?.setTitleTextAttributes([.font : UIFont.systemFont(ofSize: 18, weight: .bold), .foregroundColor : UIColor.white], for: .normal)

Вы можете изменить размер, вес (жирный, тяжелый, обычный и т.д.) и цвет, который вы предпочитаете... Надеюсь, это поможет :)

Ответ 15

Для завершения я хотел бы добавить этот метод, все еще используемый в Objective-C в 2019 году. :)

_titleLabel = [[UILabel alloc] initWithFrame:CGRectZero];
_titleLabel.text = _titleBarButtonItem.title;
_titleLabel.textColor = UIColor.whiteColor;
_titleLabel.font = [UtilityMethods appFontProDisplayBold:26.0];

[_titleLabel sizeToFit];
UIBarButtonItem *titleLabelItem = [[UIBarButtonItem alloc] initWithCustomView:_titleLabel];