13 ответов:
потому что UIBarButtonItem наследует от UIBarItem, вы можете попробовать
- (void)setTitleTextAttributes:(NSDictionary *)attributes forState:(UIControlState)stateно это только для iOS5. Для iOS 3/4, вам придется использовать пользовательский вид.
чтобы быть точным, это можно сделать, как показано ниже
[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];для удобства, вот быстрая реализация:
buttonItem.setTitleTextAttributes([ NSAttributedStringKey.font: UIFont(name: "Helvetica-Bold", size: 26.0)!, NSAttributedStringKey.foregroundColor: UIColor.green], for: .normal)
для тех, кто заинтересован в использовании
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}"конечно, вы можете изменить шрифт и размер на свое усмотрение. Я предпочитаю поместить этот код в на .
доступные атрибуты (просто добавьте их в
NSDictionary):
NSFontAttributeName: изменить шрифт сUIFontNSForegroundColorAttributeName: изменение цвета с помощьюUIColorNSShadow: добавить тень (см.NSShadowссылка на класс)(обновлено для iOS7+)
в Swift вы бы сделали это следующим образом:
backButtonItem.setTitleTextAttributes([ NSFontAttributeName : UIFont(name: "Helvetica-Bold", size: 26)!, NSForegroundColorAttributeName : UIColor.blackColor()], forState: UIControlState.Normal)
Это отличные ответы выше. Просто обновление для iOS7:
NSDictionary *barButtonAppearanceDict = @{NSFontAttributeName : [UIFont fontWithName:@"HelveticaNeue-Thin" size:18.0] , NSForegroundColorAttributeName: [UIColor whiteColor]}; [[UIBarButtonItem appearance] setTitleTextAttributes:barButtonAppearanceDict forState:UIControlStateNormal];
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)С
[ barbutton setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys: [UIFont fontWithName:@"Helvetica-Bold" size:20.0], NSFontAttributeName, [UIColor redColor], NSForegroundColorAttributeName,[UIColor blackColor],NSBackgroundColorAttributeName, nil] forState:UIControlStateNormal];
сделать это для некоторых
UIBarButtonItemsно не всем я рекомендую следующий подход.
- создать
UIBarButtonItemподкласс. Не добавляйте к нему ничего - вы будете использовать его только как пользовательский класс в раскадровке и для его внешнего вида прокси...- в раскадровке измените пользовательский класс для всех желаемых
UIBarButtonItemsв подклассе- в вашем AppDelegate импортируйте ваш
UIBarButtonItemподкласс и добавить следующую строкуapplication:didFinishLaunchingWithOptions:в моем случае я подкласса
UIBarButtonItemс единственной целью выделения текста жирным шрифтом:[[BoldBarButtonItem appearance] setTitleTextAttributes: [NSDictionary dictionaryWithObjectsAndKeys: [UIFont boldSystemFontOfSize:18.0], NSFontAttributeName,nil] forState:UIControlStateNormal];
swift 3
barButtonName.setTitleTextAttributes( [NSFontAttributeName : UIFont.systemFont(ofSize: 18.0),NSForegroundColorAttributeName : UIColor.white], for: .normal)
на Swift 4, вы можете изменить шрифт и цвет
UIBarButtonItemдобавив следующий код.addTodoBarButton.setTitleTextAttributes( [ NSAttributedStringKey.font: UIFont(name: "HelveticaNeue-Bold", size: 17)!, NSAttributedStringKey.foregroundColor: UIColor.black ], for: .normal)
Во Всем Приложении:
if let font = UIFont(name: "AvenirNext-DemiBold", size: 15) { UIBarButtonItem.appearance().setTitleTextAttributes([NSFontAttributeName: font,NSForegroundColorAttributeName:TOOLBAR_TITLE_COLOR], forState: UIControlState.Normal) }
UIBarButtonне имеют свойства, связанные с изменением шрифта. Но вы можете создать кнопку с пользовательским шрифтом, а затем добавить в UIBarButton. Это может быть решена ваша проблема
предполагая, что вы хотите поддерживать iOS4 и ранее, лучше всего создать кнопку панели с помощью
initWithCustomView:метод и предоставить свой собственный вид, который может быть что-то вроде UIButton, где вы можете легко настроить шрифт.вы также можете перетащить UIButton на панель инструментов или панель навигации в Interface Builder, если вы хотите создать кнопку с перетаскиванием, а не программно.
к сожалению, это означает создание фонового изображения кнопки себе. Нет никакого способа, чтобы настроить шрифт стандартный UIBarButtonItem до iOS5.
вы можете создать пользовательскую
UIViewпрограммно:UIView *buttonItemView = [[UIView alloc] initWithFrame:buttonFrame];затем добавьте изображения, ярлыки или все, что вам нравится, в свой пользовательский вид:
[buttonItemView addSubview:customImage]; [buttonItemView addSubview:customLabel]; ...Теперь положите его в свой
UIBarButtomItem.UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:buttonItemView];и, наконец, добавить barButtonItem к вам панель навигации.

Comments