我必须格式化为3种样式的字符串。该字符串是这样的:带动态范围的NSAttributedString
1.0000 of 2.000
1.0000
有前景的红色,of
具有更小的字体和2.000
必须是绿色的。
问题是这些数字可能在任何范围内,所以第一个和第二个数字可以由4,5,6组成任何字符。
如何执行这样的字符串格式化?
编辑----------------- 我添加了一些信息:字符串保持其格式。例如,这可能是其模板:N of N
我必须格式化为3种样式的字符串。该字符串是这样的:带动态范围的NSAttributedString
1.0000 of 2.000
1.0000
有前景的红色,of
具有更小的字体和2.000
必须是绿色的。
问题是这些数字可能在任何范围内,所以第一个和第二个数字可以由4,5,6组成任何字符。
如何执行这样的字符串格式化?
编辑----------------- 我添加了一些信息:字符串保持其格式。例如,这可能是其模板:N of N
使用NSScanner或NSRegularExpression来查找数字表达式及其片段。
让假设你有三个:
NSString *string0 = @"1.0000"; NSString *string1 = @"of"; NSString
*string2 = @"2.000";
NSString *text = [NSString stringWithFormat:@"%@ %@ %@",
string0 ,string1,string2];
//whole String attribute
NSDictionary *attribs = @{
NSForegroundColorAttributeName:[UIColor whiteColor],
NSFontAttributeName:[UIFont systemFontOfSize:10]
};
NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithString:text attributes:attribs];
NSRange string0Range = [text rangeOfString:string0];
NSRange string1Range = [text rangeOfString:string1];
NSRange string2Range = [text rangeOfString:string2];
[attributedText setAttributes:@{NSForegroundColorAttributeName:[UIColor redColor], NSFontAttributeName:[UIFont systemFontOfSize:15] range:string0Range];
[attributedText setAttributes:@{NSForegroundColorAttributeName:[UIColor blackColor], NSFontAttributeName:[UIFont systemFontOfSize:12] range:string1Range]; [attributedText setAttributes:@{NSForegroundColorAttributeName:[UIColor greenColor], NSFontAttributeName:[UIFont systemFontOfSize:15] range:string2Range];
[yourLabel setAttributedText:attributedText];
伟大的答案最适合我。谢啦 –
最简单的解决办法是:
NSString* myString = @"12.345 of 56.789";
NSMutableAttributedString * tempString = [[NSMutableAttributedString alloc] initWithString:myString];
NSRange midrange = [tempString.string rangeOfString:@"of"];
[tempString addAttributes:@{NSFontAttributeName : [UIFont fontWithName:@"HelveticaNeue" size:16.6],
NSForegroundColorAttributeName : [UIColor redColor]}
range:NSMakeRange(0, midrange.location)];
[tempString addAttributes:@{NSFontAttributeName : [UIFont fontWithName:@"HelveticaNeue" size:16.6],
NSForegroundColorAttributeName : [UIColor blackColor]}
range:midrange];
[tempString addAttributes:@{NSFontAttributeName : [UIFont fontWithName:@"HelveticaNeue" size:16.6],
NSForegroundColorAttributeName : [UIColor greenColor]}
range:NSMakeRange(midrange.location + midrange.length, tempString.length - midrange.location - midrange.length)];
yourElement.attributedText = tempString;
一点的更多信息将是有益的,就像是在类似的字符串,比如yyyyy的xxxxx,或者'单词'可能不同。 – n00bProgrammer
我已经添加了一些关于字符串格式的信息。 – MatterGoal