简体   繁体   中英

Setting custom font in UITextView with attributed string

I have a UITextView which contains an attributed string configured through storyboard. Now i want a custom font to be applied. I am doing it through code

textView.font = [UIFont fontWithName:kCustomFont size:textView.font.pointSize];

The problem is fonts get changed losing all the attributes. How do i fix it?

(Working on iOS 5 and above)

You should change it via NSMutableAttributedString's attributes.

Ie use something like:

NSMutableAttributedString *mutableString = [[NSMutableAttributedString alloc] initWithAttributedString:textView.text];
NSDictionary *attrs = [NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName, nil];
[mutableSrting addAttributes:attrs range:NSMakeRange(0, [mutableString length])];
textView.attributedText = mutableString;
[mutableString release];

What's in your kCustomFont? If the FontName is wrong, even a single Character, the standard SystemFont will be used.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM