Any way to bold part of a NSString?

2019-01-02 23:21发布

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

Approximate Distance: 120m away

Thanks!

10条回答
疯言疯语
2楼-- · 2019-01-02 23:41

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.

查看更多
我命由我不由天
3楼-- · 2019-01-02 23:42

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];
查看更多
相关推荐>>
4楼-- · 2019-01-02 23:44

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.

查看更多
Evening l夕情丶
5楼-- · 2019-01-02 23:50

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];
查看更多
登录 后发表回答