Chandran
Chandran

Reputation: 59

How to change properties of particular text in a label

I have a label and i set the text of the label programmatically. I want to set one of the word to be bold and the rest normal. However, i am unable to control the properties of the text. For example, I want this "This is an example" but am only able to achieve this "This is an example".

Upvotes: 0

Views: 57

Answers (4)

Ajay Kumar
Ajay Kumar

Reputation: 1827

Since ios6 uilabel supports attributed strings, So you can use it. For your particular case below code will work-

NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:@"This is an example"];

[string addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"HelveticaNeue-Bold" size:20.0] range:NSMakeRange(11, 7)];

label.attributedText = string;

Upvotes: 0

Mehul Sojitra
Mehul Sojitra

Reputation: 1181

Try this:

    NSString *text = @"This is an example";
    NSString *textBold = @"example";

    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:text];
    [attributedString beginEditing];
    [attributedString addAttribute:NSFontAttributeName
                             value:[UIFont boldSystemFontOfSize:20.0f]
                             range:[text rangeOfString:textBold]];

    [attributedString endEditing];
    [labelObj setAttributedText:attributedString];

Upvotes: 2

ImWH
ImWH

Reputation: 944

Let me show you a demo about the attributedText.

enter image description here

 NSDictionary*subStrAttribute1 = @{  
 NSForegroundColorAttributeName: [UIColor redColor],  
 NSStrikethroughStyleAttributeName:@2  
 };  

 NSDictionary *subStrAttribute2 =@{  
 NSForegroundColorAttributeName: [UIColor greenColor]  
};  

NSString *strDisplayText3 =@"Red and Green";  
NSMutableAttributedString *attributedText3 = [[NSMutableAttributedString alloc] initWithString:strDisplayText3];  
[attributedText3 setAttributes:subStrAttribute1 range:NSMakeRange(0,3)];  
[attributedText3 setAttributes:subStrAttribute2 range:NSMakeRange(8,5)];  
self.lblInfo3.attributedText= attributedText3;  

Upvotes: 0

Duncan C
Duncan C

Reputation: 131408

Take a look at the attributedText property of the label. It lets you assign styled text using an NSAttributedString. Explaining how to build an NSAttributedString is beyond the scope of an SO answer, but you should be able to find ample information both in the Xcode help system and online.

Upvotes: 0

Related Questions