Skip to content

Instantly share code, notes, and snippets.

@juliengdt
Created July 12, 2016 12:23
Show Gist options
  • Save juliengdt/c0059c53b26a48956989b84324528521 to your computer and use it in GitHub Desktop.
Save juliengdt/c0059c53b26a48956989b84324528521 to your computer and use it in GitHub Desktop.
Bold UILabel text by loading it to attributedText, quitted by "*--*"
- (void)boldSubText
{
NSString *textToAttribute = @"abcdefg*-hijklm-*nopqrst*-uvwxyz-*";
NSDictionary *boldAttributeDict = @{NSFontAttributeName:
[UIFont robotoBoldFontOfSize:MODAL_INFORMATION_FONT_SIZE_DESCRIPTION]};
NSArray<NSString *> *splittedSubText = [textToAttribute componentsSeparatedByString:@"*"];
NSMutableArray<NSAttributedString*> *splittedAttributedStringArray = [[NSMutableArray alloc] initWithCapacity:splittedSubText.count];
[splittedSubText enumerateObjectsUsingBlock:^(NSString *_Nonnull splittedString, NSUInteger idx, BOOL *_Nonnull stop) {
NSDictionary *toUseAttributeDict = @{};
if (([splittedString characterAtIndex:0] == '-') &&
(([splittedString characterAtIndex:splittedString.length] - 1) == '-'))
{
//need bold format
toUseAttributeDict = boldAttributeDict;
}
[splittedAttributedStringArray addObject:[[NSAttributedString alloc] initWithString:splittedString attributes:boldAttributeDict]];
}];
__block NSMutableAttributedString *attributedMutableString = [[NSMutableAttributedString alloc] init];
[splittedAttributedStringArray enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL *_Nonnull stop) {
[attributedMutableString appendAttributedString:obj];
}];
[self setText:nil];
[self setAttributedText:attributedMutableString];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment