Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSAttributedString change style to bold without changing pointSize?

I am digging into NSAttributedStrings 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!

like image 776
Michael Ochs Avatar asked Oct 19 '12 12:10

Michael Ochs


2 Answers

You can bold a string without changing its other attributes by setting the StrokeWidth attribute with a negative value.

Objective-C:

[name setAttributes:@{NSStrokeWidthAttributeName : @-3.0} range:NSRangeFromString(name.string)];

Swift:

name.setAttributes([.strokeWidth: NSNumber(value: -3.0)], range: NSRangeFromString(name.string))
like image 157
Yonat Avatar answered Sep 25 '22 08:09

Yonat


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)
    }

}
like image 25
Sakiboy Avatar answered Sep 23 '22 08:09

Sakiboy