Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSAtributedString font

How do I set the font for a NSAtributedString on the iPhone. I found online how to do it for the mac but it is not the same. When I tried to covert it to the iOS platform it didn't work. I need to set the font name and the font size.

 NSDictionary *attributes = [[NSDictionary alloc] initWithObjectsAndKeys:
                                [UIFont fontWithName:@"Helvetica" size:26], kCTFontAttributeName,
                                [UIColor blackColor], kCTForegroundColorAttributeName, nil];
like image 724
BDGapps Avatar asked Aug 02 '12 04:08

BDGapps


People also ask

How do I change font size in NSAttributedString?

Answers. You could convert NSAttributedString to NSMutableAttributedString , and then set the font attribute . If you want to set font size from Forms project , you could create a new subclass and create custom renderer for the new custom class .

What is NSAttributedString?

An NSAttributedString object manages character strings and associated sets of attributes (for example, font and kerning) that apply to individual characters or ranges of characters in the string. An association of characters and their attributes is called an attributed string.

What is NSMutableAttributedString in Swift?

A mutable string with associated attributes (such as visual style, hyperlinks, or accessibility data) for portions of its text.


2 Answers

Check out the code

infoString=@"This is an example of Attributed String";

NSMutableAttributedString *attString=[[NSMutableAttributedString alloc] initWithString:infoString];
NSInteger _stringLength=[infoString length];

UIColor *_black=[UIColor blackColor];
UIFont *font=[UIFont fontWithName:@"Helvetica-Bold" size:30.0f];
[attString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, _stringLength)];
[attString addAttribute:NSForegroundColorAttributeName value:_black range:NSMakeRange(0, _stringLength)];
like image 162
Hiren Avatar answered Nov 13 '22 12:11

Hiren


The value for kCTFontAttributeName must be a CTFontRef, not a UIFont *. You can't directly convert a UIFont to a CTFont. You should be able to just use CTFontCreateWithName to create it. You will need to use CFRelease on it when you are done, to avoid a memory leak. Check out the CTFont Reference.

Also, the value for kCTForegroundColorAttributeName must be a CGColorRef, not a UIColor *. You can fix this easily by saying [UIColor blackColor].CGColor.

UPDATE

If you're using UIKit attributed string support (which was added in iOS 6.0), you can use the NSFontAttributeName key with a UIFont as the value. You can also use the NSForegroundColorAttributeName key with a UIColor value. See NSAttributedString UIKit Additions Reference.

like image 34
rob mayoff Avatar answered Nov 13 '22 10:11

rob mayoff