Any way to bold part of a NSString?

Solution 1:

What you could do is use an NSAttributedString.

NSString *boldFontName = [[UIFont boldSystemFontOfSize:12] fontName];
NSString *yourString = ...;
NSRange boldedRange = NSMakeRange(22, 4);

NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:yourString];

[attrString beginEditing];
[attrString addAttribute:kCTFontAttributeName 
                   value:boldFontName
                   range:boldedRange];

[attrString endEditing];
//draw attrString here...

Take a look at this handy dandy guide to drawing NSAttributedString objects with Core Text.

Solution 2:

As Jacob mentioned, you probably want to use an NSAttributedString or an NSMutableAttributedString. The following is one example of how you might do this.

NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:@"Approximate Distance: 120m away"];
NSRange selectedRange = NSMakeRange(22, 4); // 4 characters, starting at index 22

[string beginEditing];

[string addAttribute:NSFontAttributeName
           value:[NSFont fontWithName:@"Helvetica-Bold" size:12.0]
           range:selectedRange];

[string endEditing];

Solution 3:

If you do not want to bother with fonts (as not every variation of font contains "Bold"), here is another way to do this. Please be aware, this is currently only available on OS X...:

NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:"Approximate Distance: 120m away"];
[attrString beginEditing];
[attrString applyFontTraits:NSBoldFontMask
                      range:NSMakeRange(22, 4)];
[attrString endEditing];

Solution 4:

The code above gave me crash when I created UILabel with this attributedString.

I used this code and it worked:

NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:string];
NSRange boldedRange = NSMakeRange(0, 1);
UIFont *fontText = [UIFont systemFontOfSize:12]; //[UIFont fontWithName:@"Lato-Bold" size:12];
NSDictionary *dictBoldText = [NSDictionary dictionaryWithObjectsAndKeys:fontText, NSFontAttributeName, nil];
[attrString setAttributes:dictBoldText range:boldedRange];

Solution 5:

Swift

Also includes getting the range of the string you want to embolden dynamically

let nameString = "Magoo"
let string = "Hello my name is \(nameString)"

let attributes = [NSFontAttributeName:UIFont.systemFontOfSize(14.0),NSForegroundColorAttributeName: UIColor.black]
let boldAttribute = [NSFontAttributeName:UIFont.boldSystemFontOfSize(14.0)]

let attributedString = NSMutableAttributedString(string: string, attributes: attributes)

let nsString = NSString(string: string)
let range = nsString.rangeOfString(nameString)

if range.length > 0 { attributedString.setAttributes(boldAttribute, range: range) }

someLabel.attributedText = attributedString