How would it be possible to include both bold and non-bold text in a uiLabel?
I'd rather not use a UIWebView.. I've also read this may be possible using NSAttributedString but I have no idea how to use that. Any ideas?
Apple achieves this in several of their apps;
Examples Screenshot:
Thanks!
– Dom
Best Answer
Update
In Swift we don't have to deal with iOS5 old stuff besides syntax is shorter so everything becomes really simple:
Swift 5
Swift 3
Usage:
Bonus: Internationalisation
Some people commented about internationalisation. I personally think this is out of scope of this question but for instructional purposes this is how I would do it
Result (Assuming English and Japanese Localizable.strings are available)
Previous answer for iOS6 and later (Objective-C still works):
In iOS6
UILabel
,UIButton
,UITextView
,UITextField
, support attributed strings which means we don't need to createCATextLayer
s as our recipient for attributed strings. Furthermore to make the attributed string we don't need to play with CoreText anymore :) We have new classes in obj-c Foundation.framework likeNSParagraphStyle
and other constants that will make our life easier. Yay!So, if we have this string:
We only need to create the attributed string:
There is a couple of good introductory blog posts here from guys at invasivecode that explain with more examples uses of
NSAttributedString
, look for "Introduction to NSAttributedString for iOS 6" and "Attributed strings for iOS using Interface Builder" :)PS: Above code it should work but it was brain-compiled. I hope it is enough :)
Old Answer for iOS5 and below
Use a CATextLayer with an NSAttributedString ! much lighter and simpler than 2 UILabels. (iOS 3.2 and above)
Example.
Don't forget to add QuartzCore framework (needed for CALayers), and CoreText (needed for the attributed string.)
Below example will add a sublayer to the toolbar of the navigation controller. à la Mail.app in the iPhone. :)
In this example I only have two different types of font (bold and normal) but you could also have different font size, different color, italics, underlined, etc. Take a look at NSAttributedString / NSMutableAttributedString and CoreText attributes string keys.
Hope it helps