I am digging into NSAttributedString
s on iOS. I have a model that is returning a persons first and last name as NSAttributesString
. (I don't know if it is a good idea to deal with attributed strings in models!?) I want the first name to be printed regular where as the last name should be printed in bold. What I don't want is to set a text size. All I found so far is this:
- (NSAttributedString*)attributedName {
NSMutableAttributedString* name = [[NSMutableAttributedString alloc] initWithString:self.name];
[name setAttributes:@{NSFontAttributeName : [UIFont boldSystemFontOfSize:[UIFont systemFontSize]]} range:[self.name rangeOfString:self.lastname]];
return name;
}
However, this will, of course, override the font size of the last name, which gives a very funny look in a UITableViewCell
where the first name will be printed in the regular text size of the cell's label and the last name will be printed very small.
Is there any way to achieve what I want?
Thanks for your help!
Here's a Swift
extension
that makes text bold, while preserving the current font attributes (and text size).
public extension UILabel {
/// Makes the text bold.
public func makeBold() {
//get the UILabel's fontDescriptor
let desc = self.font.fontDescriptor.withSymbolicTraits(.traitBold)
//Setting size to '0.0' will preserve the textSize
self.font = UIFont(descriptor: desc, size: 0.0)
}
}