我有一个像这样的字符串
NSString * string = [[NSString alloc]initwithformat: @"The current balance left is %@ out of %@",leftAmount,totalAmount];
如何在不知道收到的字符串范围的情况下,将收到的字符串颜色更改为%@。
答案 0 :(得分:2)
做这样的事,
NSString *leftAmount = @"1000";
NSString *totalAmount = @"2000";
UIColor *color = [UIColor redColor];
NSDictionary *attrs = @{ NSForegroundColorAttributeName : color };
NSAttributedString *attrStr = [[NSAttributedString alloc] initWithString:leftAmount attributes:attrs];
NSAttributedString *attrStr1 = [[NSAttributedString alloc] initWithString:totalAmount attributes:attrs];
NSMutableAttributedString * string = [[NSMutableAttributedString alloc] initWithString:@"The current balance left is "];
[string appendAttributedString:attrStr];
NSMutableAttributedString * string1 = [[NSMutableAttributedString alloc] initWithString:@" out of "];
[string1 appendAttributedString:attrStr1];
[string appendAttributedString:string1];
NSLog(@"Your Full String - %@", string);
希望这会对你有所帮助。
答案 1 :(得分:0)
做这样的事,
NSString *leftAmount,*totalAmount;
leftAmount = @"1000";
totalAmount = @"2000";
NSString * string = [NSString stringWithFormat:@"The current balance left is %@ out of %@",leftAmount,totalAmount];
NSDictionary *attribs = @{
NSForegroundColorAttributeName: [UIColor blueColor],
NSFontAttributeName: [UIFont systemFontOfSize:12]
};
NSMutableAttributedString *attributedText =
[[NSMutableAttributedString alloc] initWithString:string
attributes:attribs];
UIColor *grayColor = [UIColor colorWithRed:186.0f/255.0f green:186.0f/255.0f blue:186.0f/255.0f alpha:1];
NSRange leftAmountTextRange = [string rangeOfString:leftAmount];
[attributedText setAttributes:@{NSForegroundColorAttributeName:grayColor}
range:leftAmountTextRange];
它还会计算动态数据值范围。
我希望它能帮到你,
感谢。