Изменить свойства шрифта UINavigationBar?
У меня есть UINavigationBar, добавленный в мое представление UIViewController. Я хочу изменить свойства шрифтов. Обратите внимание, что я хочу изменить UINavigationBar not controller. В моем приложении, где я использую UINavigationController, я использую self.navigationItem.titleView = label;
для отображения пользовательской метки.
Как я могу сделать, чтобы иметь пользовательский заголовок в моем UINavigationBar?
P.S Я использую это, чтобы установить текст заголовка self.navBar.topItem.title = @"Information";
моего UINavigationBar.
Ответы
Ответ 1
Начиная с iOS 5, мы должны установить цвет текста текста и шрифт панели навигации с использованием словаря titleTextAttribute Dictionary (предопределенный словарь в ссылке класса контроллера UInavigation).
[[UINavigationBar appearance] setTitleTextAttributes:
[NSDictionary dictionaryWithObjectsAndKeys:
[UIColor blackColor], NSForegroundColorAttributeName,
[UIFont fontWithName:@"ArialMT" size:16.0], NSFontAttributeName,nil]];
Ниже приведено руководство по настройке UIElements, например, панели UInavigation, UIsegmented control, UITabBar. Это может быть полезно для вас.
http://www.raywenderlich.com/4344/user-interface-customization-in-ios-5
Ответ 2
(Это невозможно, используя новый API внешнего вида iOS 5.0).
Edit:
iOS >= 5.0:
Задайте атрибуты текстового заголовка для навигационной панели:
// Customize the title text for *all* UINavigationBars
NSDictionary *settings = @{
UITextAttributeFont : [UIFont fontWithName:@"YOURFONTNAME" size:20.0],
UITextAttributeTextColor : [UIColor whiteColor],
UITextAttributeTextShadowColor : [UIColor clearColor],
UITextAttributeTextShadowOffset : [NSValue valueWithUIOffset:UIOffsetZero]};
[[UINavigationBar appearance] setTitleTextAttributes:settings];
iOS < 5.0
UINavigationItem не имеет свойства, называемого label или что-то еще, только titleView. Вы можете установить шрифт, установив пользовательский ярлык в качестве этого заголовка
Вы можете использовать следующий код: (как предложено здесь)
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 44)];
label.font = [UIFont fontWithName:@"YOURFONTNAME" size:20.0];
label.shadowColor = [UIColor clearColor];
label.textColor =[UIColor whiteColor];
label.text = self.title;
self.navigationItem.titleView = label;
[label release];
Ответ 3
Просто поместите это в свой делегат приложения
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
От Рэя Вендерлиха:
http://www.raywenderlich.com/4344/user-interface-customization-in-ios-5
[[UINavigationBar appearance] setTitleTextAttributes:
[NSDictionary dictionaryWithObjectsAndKeys:
[UIColor colorWithRed:255.0/255.0 green:255.0/255.0 blue:255.0/255.0 alpha:1.0],
UITextAttributeTextColor,
[UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.8],
UITextAttributeTextShadowColor,
[NSValue valueWithUIOffset:UIOffsetMake(0, -1)],
UITextAttributeTextShadowOffset,
[UIFont fontWithName:@"STHeitiSC-Light" size:0.0],
UITextAttributeFont, nil]];
Ответ 4
В iOS8 swift используйте следующий код для установки шрифта:
var navigationBarAppearance = UINavigationBar.appearance()
let font = UIFont(name: "Open Sans", size: 17)
if let font = font {
navigationBarAppearance.titleTextAttributes = [NSFontAttributeName: font, NSForegroundColorAttributeName: UIColor.whiteColor()]
}
Ответ 5
ссылка ниже поможет вам.
Это зависит от того, где вы хотите установить свойства шрифта на текущей панели навигации viewController в любом месте приложения.
вы можете найти хороший учебник здесь%
http://www.appcoda.com/customize-navigation-status-bar-ios-7/?utm_campaign=iOS_Dev_Weekly_Issue_118&utm_medium=email&utm_source=iOS%2BDev%2BWeekly
Основная идея - создать экземпляр NSDictionary и заполнить его желаемым шрифтом и другими свойствами.
Я закончил с этим решением:
в вашем методе контроллера -viewDidLoad после того, как [super viewDidLoad] поместил следующие строки:
UIColor *color = [UIColor redColor];
NSShadow *shadow = [NSShadow new];
UIFont *font = [UIFont fontWithName:@"EnterYourFontName" size:20.0]
shadow.shadowColor = [UIColor greenColor];
shadow.shadowBlurRadius = 2;
shadow.shadowOffset = CGSizeMake(1.0f, 1.0f);
//fill this dictionary with text attributes
NSMutableDictionary *topBarTextAttributes = [NSMutableDictionary new];
//ios 7
topBarTextAttributes[NSForegroundColorAttributeName] = color;
//ios 6
topBarTextAttributes[UITextAttributeTextColor] = color;
//ios 6
topBarTextAttributes[UITextAttributeTextShadowOffset] = [NSValue valueWithCGSize:shadow.shadowOffset];
topBarTextAttributes[UITextAttributeTextShadowColor] = shadow.shadowColor;
//ios 7
topBarTextAttributes[NSShadowAttributeName] = shadow;
//ios 6
topBarTextAttributes[UITextAttributeFont] = font;
//ios 7
topBarTextAttributes[NSFontAttributeName] = font;
//for all the controllers uncomment this line
// [[UINavigationBar appearance]setTitleTextAttributes:topBarTextAttributes];
//for current controller uncoment this line
// self.navigationController.navigationBar.titleTextAttributes = topBarTextAttributes;
Ответ 6
Не забудьте добавить шрифт в свою цель.
Я сделал все, что можно сделать о шрифте, и я не мог загрузить его, когда на самом деле этот шрифт не был членом моей цели.
Итак, проверьте целевое членство, а также на добавленный пользовательский шрифт.