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];
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 .
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.
A mutable string with associated attributes (such as visual style, hyperlinks, or accessibility data) for portions of its text.
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)];
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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With