Как вы используете setTitleTextAttributes:forState в UIBarItem?

#ios #objective-c #swift #uinavigationcontroller #uibaritem

#iOS #objective-c #swift #uinavigationcontroller #uibaritem

Вопрос:

Как вы используете setTitleTextAttributes:forState: in UIBarItem в iOS ?

Как вы устанавливаете NSDictionary ? Не удается заставить это работать, и документация не очень ясна по этому поводу.

Из документации:

 setTitleTextAttributes:forState:
  

Устанавливает текстовые атрибуты заголовка для данного состояния управления:

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

Параметры:

атрибуты: словарь, содержащий пары ключ-значение для текстовых атрибутов. Вы можете указать шрифт, цвет текста, цвет тени текста и смещение тени текста, используя ключи, перечисленные в NSString UIKit Additions Reference.

состояние: состояние элемента управления, для которого вы хотите установить текстовые атрибуты для заголовка.

Ответ №1:

Пример кода:

 [[UIBarItem appearance] setTitleTextAttributes:
[NSDictionary dictionaryWithObjectsAndKeys:
[UIColor colorWithRed:220.0/255.0 green:104.0/255.0 blue:1.0/255.0 alpha:1.0], UITextAttributeTextColor, 
[UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:1.0], UITextAttributeTextShadowColor, 
[NSValue valueWithUIOffset:UIOffsetMake(0, 1)], UITextAttributeTextShadowOffset, 
[UIFont fontWithName:@"AmericanTypewriter" size:0.0], UITextAttributeFont, nil] 
forState:UIControlStateNormal];
  

Комментарии:

1. У NSValue нет метода valueWithUIOffset. Моя программа потерпела крах на этом этапе вашего кода.

2. Смотрите developer.apple.com/library/ios/#DOCUMENTATION/UIKit/Reference/…

3. UITextAttribute устарел, начиная с iOS 7, вместо этого следует использовать значения класса NSAttributedString, например, вместо UITextAttributeTextColor следует использовать NSForegroundColorAttributeName

Ответ №2:

Swift 5.0:

 // Bar title text color
let shadow = NSShadow()
shadow.shadowColor = UIColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
shadow.shadowOffset = CGSize(width: 0, height: 1)
let color : UIColor = UIColor(red: 220.0/255.0, green: 104.0/255.0, blue: 1.0/255.0, alpha: 1.0)
let titleFont : UIFont = UIFont(name: "AmericanTypewriter", size: 16.0)!

let attributes = [
    NSAttributedString.Key.foregroundColor : color,
    NSAttributedString.Key.shadow : shadow,
    NSAttributedString.Key.font : titleFont
]
self.navigationItem.rightBarButtonItem?.setTitleTextAttributes(attributes, for: .normal)

// Or you can use
UIBarItem.appearance().setTitleTextAttributes(attributes, for: .normal)
  

Swift 4.0:

 // Bar title text color
let shadow = NSShadow()
shadow.shadowColor = UIColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
shadow.shadowOffset = CGSize(width: 0, height: 1)
let color : UIColor = UIColor(red: 220.0/255.0, green: 104.0/255.0, blue: 1.0/255.0, alpha: 1.0)
let titleFont : UIFont = UIFont(name: "AmericanTypewriter", size: 16.0)!

let attributes = [
        NSAttributedStringKey.foregroundColor : color,
        NSAttributedStringKey.shadow : shadow,
        NSAttributedStringKey.font : titleFont
    ]

self.navigationItem.rightBarButtonItem?.setTitleTextAttributes(attributes, for: UIControlState.normal)
// Or you can use
UIBarItem.appearance().setTitleTextAttributes(attributes, for: UIControlState.normal)
  

Код Objective C:

 NSShadow *shadow = [NSShadow new];
[shadow setShadowColor:[UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:1.0]];
[shadow setShadowOffset:CGSizeMake(0, 1)];

NSDictionary *attributes = @{
                                NSForegroundColorAttributeName: [UIColor colorWithRed:220.0/255.0 green:104.0/255.0 blue:1.0/255.0 alpha:1.0],
                                NSShadowAttributeName: shadow,
                                NSFontAttributeName: [UIFont fontWithName:@"AmericanTypewriter" size:16.0]
                             };

[self.navigationItem.rightBarButtonItem setTitleTextAttributes:attributes forState: UIControlStateNormal];

// Or you can use.

[[UIBarItem appearance] setTitleTextAttributes:attributes forState: UIControlStateNormal];
  

Комментарии:

1. Swift 4 на самом деле следующий: [NSAttributedStringKey.foregroundColor: color] Вам следует обновить свой код.

Ответ №3:

Вот код phix23, только с обновленным и, я думаю, более чистым синтаксисом:

 [[UIBarItem appearance] setTitleTextAttributes:@{
                      UITextAttributeTextColor: [UIColor colorWithRed:220.0/255.0 green:104.0/255.0 blue:1.0/255.0 alpha:1.0],
                UITextAttributeTextShadowColor: [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:1.0],
               UITextAttributeTextShadowOffset: [NSValue valueWithUIOffset:UIOffsetMake(0, 1)],
                           UITextAttributeFont: [UIFont fontWithName:@"AmericanTypewriter" size:0.0]}
                                      forState: UIControlStateNormal];
  

Ответ №4:

 [self.tabBarItem setTitleTextAttributes:[NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:[UIColor whiteColor], nil] forKeys:[NSArray arrayWithObjects:UITextAttributeTextColor, nil]] forState:UIControlStateNormal];
  

Ответ №5:

Swift5 устанавливает UIBarItem цвет заголовка

 let attributes = [
    NSAttributedString.Key.foregroundColor : UIColor.orange,
    NSAttributedString.Key.font : UIFont.systemFont(ofSize: 20)
]
vc.tabBarItem.setTitleTextAttributes(attributes, for: .normal)