Cambiar la fuente de un UIBarButtonItem


UIToolbar con UIBarButtonItem

Tengo un UIBarButtonItem en mi UIToolbartitulado Hecho. Ahora quiero cambiar la fuente por defecto "Trebuchet MS" con Negrita. ¿Cómo puedo hacer eso?

Author: Josh Caswell, 2012-01-13

13 answers

Debido a que UIBarButtonItem hereda de UIBarItem, puede probar

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

Pero esto es solo para iOS5. Para iOS 3/4, tendrá que usar una vista personalizada.

 115
Author: teriiehina,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-18 23:37:41

Para ser precisos, esto se puede hacer de la siguiente manera

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

O con sintaxis literal de objeto:

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

Para mayor comodidad, aquí está la implementación de Swift:

buttonItem.setTitleTextAttributes([
        NSAttributedStringKey.font: UIFont(name: "Helvetica-Bold", size: 26.0)!,
        NSAttributedStringKey.foregroundColor: UIColor.green],
    for: .normal)
 196
Author: mask,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-05 17:20:48

Para aquellos interesados en usar UIAppearance para estilizar sus fuentes UIBarButtonItem a lo largo de la aplicación, se puede lograr usando esta línea de código:

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

O para un solo UIBarButtonItem (no para toda la aplicación), si tiene una fuente personalizada para un botón en particular:

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}"

Por supuesto, puede cambiar la fuente y el tamaño a lo que desee. Prefiero poner este código en el archivo AppDelegate.m en la sección didFinishLaunchingWithOptions.

Atributos disponibles (solo agrégalos a la NSDictionary):

  • NSFontAttributeName: Cambiar la fuente con un UIFont
  • NSForegroundColorAttributeName: Cambiar de color con un UIColor
  • NSShadow: Añadir una sombra paralela (ver NSShadow class reference)

(Actualizado para iOS7+)

 102
Author: rog,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-02 18:55:05

En Swift harías esto de la siguiente manera:

backButtonItem.setTitleTextAttributes([
        NSFontAttributeName : UIFont(name: "Helvetica-Bold", size: 26)!,
        NSForegroundColorAttributeName : UIColor.blackColor()],
    forState: UIControlState.Normal)
 19
Author: Antoine,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-08 12:33:55

Estas son grandes respuestas anteriores. Solo actualizando para iOS7:

NSDictionary *barButtonAppearanceDict = @{NSFontAttributeName : [UIFont fontWithName:@"HelveticaNeue-Thin" size:18.0] , NSForegroundColorAttributeName: [UIColor whiteColor]};
    [[UIBarButtonItem appearance] setTitleTextAttributes:barButtonAppearanceDict forState:UIControlStateNormal];
 16
Author: David DelMonte,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-12-23 23:20:54

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];
 15
Author: Anbu.karthik,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-29 04:41:31

Para hacer esto para algunos UIBarButtonItems pero no todos recomiendo el siguiente enfoque.

  1. Crea una subclase UIBarButtonItem. No agregue nada a él: solo lo usará como una clase personalizada en el guion gráfico y para su proxy de apariencia...
  2. En su storyboard, cambie la clase personalizada para todos los UIBarButtonItems deseados a su subclase
  3. En tu AppDelegate importa tu subclase UIBarButtonItem y añade la siguiente línea a application:didFinishLaunchingWithOptions:

En mi caso subclase UIBarButtonItem para el único propósito del texto en negrita:

[[BoldBarButtonItem appearance] setTitleTextAttributes:
  [NSDictionary dictionaryWithObjectsAndKeys: 
    [UIFont boldSystemFontOfSize:18.0], NSFontAttributeName,nil] 
                                              forState:UIControlStateNormal];
 7
Author: Kyle Clegg,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-04-08 09:33:20

Swift 3

barButtonName.setTitleTextAttributes( [NSFontAttributeName : UIFont.systemFont(ofSize: 18.0),NSForegroundColorAttributeName : UIColor.white], for: .normal) 
 2
Author: venky,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-20 21:03:00

{[2] {} En[3]}Swift 4, puede cambiar la fuente y el color de UIBarButtonItem añadiendo el siguiente código.

addTodoBarButton.setTitleTextAttributes(
        [
        NSAttributedStringKey.font: UIFont(name: "HelveticaNeue-Bold", size: 17)!,
        NSAttributedStringKey.foregroundColor: UIColor.black
        ], for: .normal)
 2
Author: Vinoth Vino,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-19 14:14:00

A lo largo de la aplicación:

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

    }
 1
Author: Yogesh Lolusare,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-11-18 07:15:55

UIBarButton no tiene propiedades relacionadas con cambiar la fuente. Pero puede crear un botón con fuente personalizada y luego agregarlo a UIBarButton. Se puede resolver su problema

 0
Author: Hiren,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-01-13 11:46:54

Asumiendo que desea soportar iOS4 y anteriores, su mejor apuesta es crear un botón de barra usando el método initWithCustomView: y proporcionar su propia vista que podría ser algo así como un UIButton donde puede personalizar fácilmente la fuente.

También puede arrastrar un UIButton a una barra de herramientas o barra de navegación en Interface Builder si desea crear el botón con arrastrar y soltar en lugar de mediante programación.

Desafortunadamente, esto significa crear la imagen de fondo del botón usted mismo. No hay manera para personalizar la fuente de un UIBarButtonItem estándar antes de iOS5.

 0
Author: Nick Lockwood,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-01-13 11:50:58

Puede crear un UIView personalizado mediante programación:

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

Luego agrega imágenes, etiquetas o lo que quieras a tu vista personalizada:

[buttonItemView addSubview:customImage];

[buttonItemView addSubview:customLabel];

...

Ahora ponlo en tu UIBarButtomItem.

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

Y finalmente añadir barButtonItem a la barra de navegación.

 0
Author: Beppe,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-01-13 13:04:14