Reputation: 33138
NSString * strTimeBefore = [timeBefore componentsJoinedByString:@" "];
NSString * strTimeAfter = [timeAfter componentsJoinedByString:@" "];
I want the resulting string to be an NSAttributedString where the time in strTimeAfter is in bold
Upvotes: 0
Views: 920
Reputation: 15035
Take two attribute string in that store your first string into one attribute string without changing its attributes, In second attribute string store your second string with changing its attibutes and then append both attribute string into one NSMutableAttributeString
Try like this below:-
NSString * strTimeBefore = [timeBefore componentsJoinedByString:@" "];
NSString * strTimeAfter = [timeAfter componentsJoinedByString:@" "];
NSAttributedString *attrBeforeStr=[[NSAttributedString alloc]initWithString:strTimeBefore];
NSMutableDictionary *attributes = [[NSMutableDictionary alloc] init];
[attributes setObject:[NSColor yellowColor] forKey:NSBackgroundColorAttributeName];
NSFont *font = [[NSFontManager sharedFontManager] fontWithFamily:@"Arial" traits:NSBoldFontMask weight:5 size:14];
[attributes setObject:font forKey:NSFontAttributeName];
NSAttributedString *attrAftStr=[[NSAttributedString alloc]initWithString:strTimeAfter attributes:];
NSMutableAttributedString *string=[[NSMutableAttributedString alloc] init];
[string appendAttributedString:attrBeforeStr];
[string appendAttributedString:strTimeAfter];
Note: You can change font color as well in attribute string, if it is required.
Upvotes: 0
Reputation: 89559
You probably want something like:
NSString *boldFontName = [[UIFont boldSystemFontOfSize:12] fontName];
NSString *yourString = [NSString stringWithFormat:@"%@ %@", strTimeBefore, strTimeAfter;
// start at the end of strTimeBefore and go the length of strTimeAfter
NSRange boldedRange = NSMakeRange([strTimeBefore length] + 1, [strTimeAfter length]);
NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:yourString];
[attrString beginEditing];
[attrString addAttribute:NSFontAttributeName
value:boldFontName
range:boldedRange];
[attrString endEditing];
And my answer is cribbed from Jacob's answer to this very closely related question.
Upvotes: 1