NSString * strTimeBefore = [timeBefore componentsJoinedByString:@" "];
NSString * strTimeAfter = [timeAfter componentsJoinedByString:@" "];
我希望生成的字符串是NSAttributedString,其中strTimeAfter中的时间以粗体显示
答案 0 :(得分:1)
您可能需要以下内容:
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];
我的回答是雅各布对这个very closely related question的回答。
答案 1 :(得分:0)
将第一个字符串中的两个属性字符串存储到一个属性字符串中,而不更改其属性。在第二个属性字符串中存储第二个字符串并更改其属性,然后将两个属性字符串追加到一个NSMutableAttributeString
尝试这样下面: -
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];
注意:如果需要,您也可以在属性字符串中更改字体颜色。