Могу ли я установить свойство attributedText для UILabel

Могу ли я установить свойство attributedText объекта UILabel? Я попробовал следующий код:

UILabel *label = [[UILabel alloc] init];
label.attributedText = @"asdf";

Но это дает такую ​​ошибку:

Свойство attributedText не найдено в объекте типа 'UILabel *'

#import <CoreText/CoreText.h> не работает


person Shamsiddin    schedule 14.06.2012    source источник
comment
Воспользуйтесь этой ссылкой stackoverflow.com/questions/3786528 /   -  person Rajneesh071    schedule 14.06.2012
comment
я думаю, что это полезно для вас stackoverflow.com / questions / 3786528 /   -  person Rajneesh071    schedule 14.06.2012


Ответы (6)


К сожалению, UILabel не поддерживает строки с атрибутами. Вместо этого вы можете использовать OHAttributedLabel.

Обновление. Начиная с iOS6, UILabel поддерживает строки с атрибутами. См. Ссылка на UILabel или ответ Майкла Кесслера ниже для получения дополнительных сведений.

person Chaitanya Gupta    schedule 14.06.2012
comment
Начиная с iOS 6, UILabel поддерживает строки с атрибутами через свойство attributedText. - person Greg; 30.11.2012

Вот полный пример того, как использовать текст с атрибутами на этикетке:

NSString *redText = @"red text";
NSString *greenText = @"green text";
NSString *purpleBoldText = @"purple bold text";

NSString *text = [NSString stringWithFormat:@"Here are %@, %@ and %@", 
                  redText,  
                  greenText,  
                  purpleBoldText];

// If attributed text is supported (iOS6+)
if ([self.label respondsToSelector:@selector(setAttributedText:)]) {

    // Define general attributes for the entire text
    NSDictionary *attribs = @{
                              NSForegroundColorAttributeName: self.label.textColor,
                              NSFontAttributeName: self.label.font
                              };
    NSMutableAttributedString *attributedText = 
        [[NSMutableAttributedString alloc] initWithString:text
                                               attributes:attribs];

    // Red text attributes
    UIColor *redColor = [UIColor redColor];
    NSRange redTextRange = [text rangeOfString:redText];// * Notice that usage of rangeOfString in this case may cause some bugs - I use it here only for demonstration
    [attributedText setAttributes:@{NSForegroundColorAttributeName:redColor}
                            range:redTextRange];

    // Green text attributes
    UIColor *greenColor = [UIColor greenColor];
    NSRange greenTextRange = [text rangeOfString:greenText];// * Notice that usage of rangeOfString in this case may cause some bugs - I use it here only for demonstration
    [attributedText setAttributes:@{NSForegroundColorAttributeName:greenColor}
                            range:greenTextRange];

    // Purple and bold text attributes
    UIColor *purpleColor = [UIColor purpleColor];
    UIFont *boldFont = [UIFont boldSystemFontOfSize:self.label.font.pointSize];
    NSRange purpleBoldTextRange = [text rangeOfString:purpleBoldText];// * Notice that usage of rangeOfString in this case may cause some bugs - I use it here only for demonstration
    [attributedText setAttributes:@{NSForegroundColorAttributeName:purpleColor,
                                    NSFontAttributeName:boldFont}
                            range:purpleBoldTextRange];

    self.label.attributedText = attributedText;
}
// If attributed text is NOT supported (iOS5-)
else {
    self.label.text = text;
}
person Michael Kessler    schedule 30.05.2013
comment
Имейте в виду, что использование rangeOfString подобным образом вызовет ошибки, если одни части текста являются подмножеством других. Вам лучше самостоятельно определять диапазоны, используя NSRange, а длину струн определять вручную. - person owencm; 28.07.2013
comment
@owencm, вы абсолютно правы. Этот код нельзя использовать ни в какой ситуации, особенно когда текст приходит из Интернета. Этот фрагмент кода просто демонстрирует, как использовать attributedText вместе с обратной совместимостью ... - person Michael Kessler; 30.07.2013
comment
Хороший ответ. Но черт возьми, этот тупой API. - person aroth; 19.05.2014
comment
@aroth, это способ сделать это в коде и по-прежнему поддерживать более старые версии ОС, в которых эта функция недоступна. Если вы поддерживаете только iOS6 + (большинство приложений сегодня), вы можете сделать это в конструкторе интерфейсов - намного чище ... - person Michael Kessler; 19.05.2014
comment
это не работает, если у вас есть один и тот же текст более одного раза и применяются разные атрибуты .. :( вам нужно иметь уникальные строки. - person Ankur; 29.01.2015
comment
@Ankur, как я уже упоминал в одном из комментариев выше, этот код нельзя использовать ни в какой ситуации, особенно когда тексты поступают из Интернета. Этот фрагмент кода просто демонстрирует, как использовать attributedText вместе с обратной совместимостью ... - person Michael Kessler; 08.02.2015

для Swift 4:

iOS 11 и xcode 9.4

  let str = "This is a string which will shortly be modified into AtrributedString"

  var attStr = NSMutableAttributedString.init(string: str)

  attStr.addAttribute(.font,
                value: UIFont.init(name: "AppleSDGothicNeo-Bold", size: 15) ?? "font not found",
                range: NSRange.init(location: 0, length: str.count))

  self.textLabel.attributedText = attStr
person Tanvir Nayem    schedule 03.07.2018

Для людей, использующих Swift, вот однострочник:

myLabel.attributedText = NSMutableAttributedString(string: myLabel.text!, attributes: [NSFontAttributeName:UIFont(name: "YourFont", size: 12), NSForegroundColorAttributeName: UIColor.whiteColor()])
person Rob    schedule 15.01.2015

Итак, вот код, чтобы иметь разные свойства для подстрок строки.

 NSString *str=@"10 people likes this";
    NSString *str2=@"likes this";
    if ([str hasSuffix:str2])
    {
        NSMutableAttributedString * string = [[NSMutableAttributedString alloc] initWithString:str];

    // for string 1 //

        [string addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(0,str.length-str2.length)];
         [string addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:14] range:NSMakeRange(0,str.length-str2.length)];
  // for string 2 //

        [string addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange((str.length-str2.length),str2.length)];
        [string addAttribute:NSFontAttributeName value:[UIFont italicSystemFontOfSize:12] range:NSMakeRange((str.length-str2.length),str2.length)];
        label.attributedText=string;
    }
    else
    {
        label.text =str;

    }
person bharathi kumar    schedule 20.01.2015

Надеюсь это поможет ;)

NSMutableAttributedString* attrStr = [NSMutableAttributedString attributedStringWithString:@"asdf"];
[attrStr setFont:[UIFont systemFontOfSize:12]];
[attrStr setTextColor:[UIColor grayColor]];
[attrStr setTextColor:[UIColor redColor] range:NSMakeRange(0,5)];
lbl.attributedText = attrStr;
person Blade    schedule 14.06.2012
comment
Просто используйте приведенный выше код, и он должен работать. Больше нечего делать. - person Blade; 14.06.2012
comment
выдает ошибку: свойство attributedText не найдено для объекта типа 'UILabel *' - person Shamsiddin; 14.06.2012
comment
Попробуйте импортировать CoreText.framework. А затем вставьте свой .h файл #import ‹CoreText / CoreText.h› - person Blade; 14.06.2012
comment
снова та же ошибка дает: свойство attributedText не найдено в объекте типа 'UILabel *' - person Shamsiddin; 14.06.2012
comment
Затем попробуйте использовать этот stackoverflow.com/questions/ 3786528 / - person Blade; 14.06.2012
comment
Это не то, как вы используете NSMutableAttributedString, поэтому приведенный выше код просто не будет работать. Аналогичный и простой пример приведен в этом ответе: stackoverflow.com/a/11291275/67397 - person leolobato; 04.09.2013