2012-06-14 3 views
41

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

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

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

Property "attributedText" not found on object of type 'UILabel *'

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

+0

Используйте эту ссылку http://stackoverflow.com/questions/3786528/iphone-ipad-how-exactly-use-nsattributedstring – Rajneesh071

+0

я думаю, что это полезно для и HTTP : //stackoverflow.com/questions/3786528/iphone-ipad-how-exactly-use-nsattributedstring – Rajneesh071

ответ

31

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

Обновление: Поскольку iOS6, UILabel поддерживает привязанные строки. См. UILabel reference или ответ Майкла Кесслера ниже для более подробной информации.

+37

Начиная с iOS 6, UILabel поддерживает атрибутные строки через свойство attributedText. – Greg

1

Надежда это помогает;)

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; 
+0

Просто используйте приведенный выше код и он должен работать. Больше нечего делать. – Blade

+0

дает ошибку: Свойство "attributedText" не найдено на объекте типа 'UILabel *' – Shamsiddin

+0

Попробуйте импортировать «CoreText.framework». И затем добавьте в свой .h файл #import Blade

196

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

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; 
} 
+1

Помните, что использование rangeOfString, как это приведет к ошибкам, если некоторые части текста являются подмножеством других. Вам лучше поработать с помощью NSRange и выработать длину строк вручную. – owencm

+0

@owencm, вы абсолютно правы. Этот код нельзя использовать ни в какой ситуации, особенно если тексты не поступают из Интернета. Этот фрагмент кода просто демонстрирует, как использовать атрибутText вместе с обратной совместимостью ... –

+0

Хороший ответ. Но черт возьми, это API _obtuse_. – aroth

8
NSString *str1 = @"Hi Hello, this is plain text in red"; 

NSString *cardName = @"This is bold text in blue"; 

NSString *text = [NSString stringWithFormat:@"%@\n%@",str1,cardName]; 


// Define general attributes for the entire text 
NSDictionary *attribs = @{ 
          NSForegroundColorAttributeName:[UIColor redColor], 
          NSFontAttributeName: [UIFont fontWithName:@"Helvetica" size:12] 
          }; 
NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithString:text attributes:attribs]; 


UIFont *boldFont = [UIFont fontWithName:@"Helvetica-Bold" size:14.0]; 
NSRange range = [text rangeOfString:cardName]; 
[attributedText setAttributes:@{NSForegroundColorAttributeName: [UIColor blueColor], 
           NSFontAttributeName:boldFont} range:range]; 


myLabel = [[UILabel alloc] initWithFrame:CGRectZero]; 

myLabel.attributedText = attributedText; 
5

Для людей, использующих быстр, вот один вкладыш:

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

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

NSString *[email protected]"10 people likes this"; 
    NSString *[email protected]"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; 

    } 
0
UIFont *font = [UIFont boldSystemFontOfSize:12]; 
NSDictionary *fontDict = [NSDictionary dictionaryWithObject: font forKey:NSFontAttributeName]; 
NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:@" v 1.2.55" attributes: fontDict]; 

UIFont *fontNew = [UIFont boldSystemFontOfSize:17]; 
NSDictionary *fontDictNew = [NSDictionary dictionaryWithObject: fontNew forKey:NSFontAttributeName]; 
NSMutableAttributedString *attrStringNew = [[NSMutableAttributedString alloc] initWithString:@“Application” attributes: fontDictNew]; 
[attrStringNew appendAttributedString: attrString]; 
self.vsersionLabel.attributedText = attrStringNew; 
Смежные вопросы