Cambiar la fuente de un UIBarButtonItem
Tengo un UIBarButtonItem
en mi UIToolbar
titulado Hecho. Ahora quiero cambiar la fuente por defecto "Trebuchet MS" con Negrita. ¿Cómo puedo hacer eso?
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.
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)
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 unUIFont
-
NSForegroundColorAttributeName
: Cambiar de color con unUIColor
-
NSShadow
: Añadir una sombra paralela (verNSShadow
class reference)
(Actualizado para iOS7+)
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)
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];
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];
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.
- 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... - En su storyboard, cambie la clase personalizada para todos los
UIBarButtonItems
deseados a su subclase - En tu AppDelegate importa tu subclase
UIBarButtonItem
y añade la siguiente línea aapplication: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];
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)
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)
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)
}
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
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.
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.
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