公告
财富商城
积分规则
提问
发文
2019-01-02 23:21发布
爷、活的狠高调
Is there any way to bold only part of a string? For example:
Approximate Distance: 120m away
Thanks!
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.
As Jacob mentioned, you probably want to use an NSAttributedString or an NSMutableAttributedString. The following is one example of how you might do this.
NSAttributedString
NSMutableAttributedString
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];
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.
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];
最多设置5个标签!
I coupled @Jacob Relkin and @Andrew Marin answers, otherwise, I got the crashes. Here is the answer for iOS9:
I took a look at the official documentation: 1 and 2.
As Jacob mentioned, you probably want to use an
NSAttributedString
or anNSMutableAttributedString
. The following is one example of how you might do this.What you could do is use an
NSAttributedString
.Take a look at this handy dandy guide to drawing
NSAttributedString
objects with Core Text.If you don't want to hardcode the font or/and the size try this code for bolding full strings: