79

Is there any way to bold only part of a string? For example:

Approximate Distance: 120m away

Thanks!

1
  • 3
    It depends on what you're displaying it in, because a string is just a series of characters and doesn't contain formatting information.
    – BoltClock
    May 16, 2011 at 6:07

11 Answers 11

103

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.

11
  • 2
    Can anyone tell me what "kCTFontAttributeName" is defined as?
    – Sohan
    Nov 2, 2011 at 8:36
  • 1
    Oops. just figured that it is a constant that is defined in the CTFont.h in your CoreText framework.
    – Sohan
    Nov 2, 2011 at 9:00
  • 8
    it says: Use of undefined identifier 'kCTFontAttributeName', did you mean 'NSFontAttributeName'? What's wrong about that? can i use NSFontAttributeName instead?
    – tester
    Oct 10, 2012 at 10:03
  • 1
    @tester Which version of iOS are you building against? I think NSFontAttributeName is only available on OS X. Oct 10, 2012 at 15:27
  • 11
    This one does not work on iOS7 (crashes with exc_bad_access). The reason for it is you have to send the font instead of the font name as part of the message. @Chris Frederick does it correctly below. Dec 24, 2013 at 15:47
62

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];
6
  • 1
    When I try this, I get Use of Undeclared identifier 'NSFont' on the value: line. How do I fix this? Feb 16, 2014 at 4:42
  • This is a great example. You're missing an @ around the example string after your initWithString: method on the first line. :) Mar 26, 2014 at 23:11
  • 12
    @ZuluDeltaNiner If you are using iOS, replace NSFont with UIFont Mar 26, 2014 at 23:21
  • I figured it out a while ago; I guess I forgot to delete my comment. Mar 27, 2014 at 4:00
  • 2
    Saved me! Answer to this question needs to be edited I spent like two hours on this &^%# May 22, 2014 at 6:04
14

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];
4
  • NSBoldFontMask is undeclared for iOS? Any replacement? Mar 3, 2015 at 3:43
  • @coolcool1994 - Sorry, not that I'm aware. I will edit my answer to clarify that this is OS X only trick...
    – yura
    Mar 4, 2015 at 5:06
  • beginEditing and endEditing are 'Overridden by subclasses to buffer or optimize a series of changes to the receiver’s characters or attributes' and not needed here. Otherwise, this was exactly what I needed. Jan 26, 2019 at 0:46
  • Probably helpful here: you can get a mutable copy of an NSAttributedString *string instance by calling [string mutableCopy].
    – bassim
    Apr 21, 2021 at 9:28
6

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];
0
6

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
4

To bold a string without hardcoding its font, you can use the StrokeWidth attribute with a negative value:

let s = NSMutableAttributedString(string: "Approximate Distance: 120m away")
s.addAttribute(NSStrokeWidthAttributeName, value: NSNumber(value: -3.0), range: NSRange(22..<26))
2

An NSString is just a data container. It doesn't contain any details about presentation concerns.

It sounds like what you probably want to do is bold part of the UILabel that is being used to display your string. Which I don't think you can do. But you could always break the UI down into three labels, one for "Approximate Distance:", one for "120 m", and one for "away". Place them in-line with each other and you should get the desired effect.

Another option might be to use a UIWebView and a little bit of markup to display your string with embedded formatting information, as discussed here:

http://iphoneincubator.com/blog/windows-views/display-rich-text-using-a-uiwebview

2

In Xamarin ios you can bold part of a NSString this way:

public static NSMutableAttributedString BoldRangeOfString (string str, float fontSize, int startRange, int lengthRange)
    {
        var firstAttributes = new UIStringAttributes {
            Font = UIFont.BoldSystemFontOfSize(fontSize)
        };

        NSMutableAttributedString boldString = new NSMutableAttributedString (str);
        boldString.SetAttributes (firstAttributes.Dictionary, new NSRange (startRange, lengthRange));
        return boldString;
    }    

and call this method:

myLabel = new UILabel (); 
...
myLabel.AttributedText = BoldRangeOfString("my text", fontSize, startRange, lengthRange);    
2
  • 6
    The question was not about Xamarin.
    – Zia
    Feb 19, 2015 at 1:30
  • 4
    Xamarin works with same object NSString, the question did not specify which language the answer should be in. I came here looking for Xamarin syntax of doing this. Valid answer.
    – root
    Nov 8, 2015 at 19:45
2

I coupled @Jacob Relkin and @Andrew Marin answers, otherwise, I got the crashes. Here is the answer for iOS9:

UIFont *boldFont = [UIFont boldSystemFontOfSize:12];
NSString *yourString = @"Approximate Distance: 120m away";
NSRange boldedRange = NSMakeRange(22, 4);

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

[attrString beginEditing];
[attrString addAttribute:NSFontAttributeName 
                   value:boldFont
                   range:boldedRange];

[attrString endEditing];

I took a look at the official documentation: 1 and 2.

2

Shorter way using Swift5+

let labelNotes = UILabel()  //or UITextView(), etc...
let attributedNotes = NSMutableAttributedString(string: "Bold: some stuff not bold")
attributedNotes.addAttribute(NSAttributedString.Key.font, value: UIFont.boldSystemFont(ofSize: 14), range: NSRange(location: 0, length: 5))
labelNotes.attributedText = attributedNotes
0

If you don't want to hardcode the font or/and the size try this code for bolding full strings:

NSMutableAttributedString *myString = [[NSMutableAttributedString alloc] initWithString:mainString];
[myString beginEditing];
[myString addAttribute:NSStrokeWidthAttributeName
                         value:[[NSNumber alloc] initWithInt: -3.f]
                         range:NSMakeRange(0, [mainString length])];
[myString endEditing];

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.