У меня есть UIBarButtonItem
в моем UIToolbar
под названием Готово. Теперь я хочу изменить шрифт по умолчанию на "Trebuchet MS" с помощью Bold. Пожалуйста, помогите мне в решении этой задачи.
Поскольку 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];
Для удобства здесь реализация Swift:
buttonItem.setTitleTextAttributes([
NSFontAttributeName: UIFont(name: "Helvetica-Bold", size: 26.0)!,
NSForegroundColorAttributeName: UIColor.greenColor()],
forState: UIControlState.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.0/4
UIBarButtonItem.appearance().setTitleTextAttributes(
[
NSFontAttributeName : UIFont(name: "HelveticaNeue-Light", size: 12)!,
NSForegroundColorAttributeName : UIColor.white,
], for: .normal)
Или для одного UIBarButtonItem (не для всех приложений), если у вас есть собственный шрифт для одной кнопки в частности:
let barButtonItem = UIBarButton()
barButtonItem.setTitleTextAttributes([
NSFontAttributeName : UIFont(name: "FontAwesome", size: 26)!,
NSForegroundColorAttributeName : UIColor.white,
], for: .normal)
barButtonItem.title = "\u{f02a}"
Конечно, вы можете изменить шрифт и размер на все, что захотите. Я предпочитаю поместить этот код в файл AppDelegate.m
в разделе didFinishLaunchingWithOptions
.
Доступные атрибуты (просто добавьте их в NSDictionary
):
NSFontAttributeName
: Изменить шрифт с помощью UIFont
NSForegroundColorAttributeName
: изменить цвет с помощью UIColor
NSShadow
: Добавить тень (см. 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)
Objective-C
[ barbutton setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
[UIFont fontWithName:@"Helvetica-Bold" size:20.0], NSFontAttributeName,
[UIColor redColor], NSForegroundColorAttributeName,[UIColor blackColor],NSBackgroundColorAttributeName,
nil]
forState:UIControlStateNormal];
Чтобы сделать это для некоторых UIBarButtonItems
, но не для всех, я рекомендую следующий подход.
UIBarButtonItem
. Не добавляйте ничего к нему - вы будете использовать его только как пользовательский класс в раскадровке и для своего внешнего вида прокси...UIBarButtonItems
для вашего подкласса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)
В приложении:
if let font = UIFont(name: "AvenirNext-DemiBold", size: 15) {
UIBarButtonItem.appearance().setTitleTextAttributes([NSFontAttributeName: font,NSForegroundColorAttributeName:TOOLBAR_TITLE_COLOR], forState: UIControlState.Normal)
}
Вы можете создать пользовательский UIView
программно:
UIView *buttonItemView = [[UIView alloc] initWithFrame:buttonFrame];
Затем добавьте изображения, ярлыки или все, что вам нравится, в пользовательский вид:
[buttonItemView addSubview:customImage];
[buttonItemView addSubview:customLabel];
...
Теперь поставьте его в свой UIBarButtomItem
.
UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:buttonItemView];
И, наконец, добавьте barButtonItem в панель навигации.
UIBarButton
не имеют свойства, связанные с изменением шрифта. Но вы можете создать кнопку с пользовательским шрифтом, а затем добавить в UIBarButton. Это может решить вашу проблему.
Предполагая, что вы хотите поддерживать iOS4 и более ранние версии, лучше всего создать кнопку бара с помощью метода initWithCustomView:
и предоставить свой собственный вид, который может быть чем-то вроде UIButton, где вы можете легко настроить шрифт.
Вы также можете перетащить UIButton на панель инструментов или панель навигации в Interface Builder, если вы хотите создать кнопку с перетаскиванием вместо программного.
К сожалению, это означает создание фонового изображения кнопки самостоятельно. Нет способа настроить шрифт стандартного UIBarButtonItem до iOS5.