1、前言
- 双语显示上下显示一大一小会好看点,同时最好支持设置文字颜色,但有时候只想使用默认的参数。此时动态多参数应运而生。
2、解决
#define GCLocal(...) [self local:__VA_ARGS__, nil]
- (id)local:(NSString *)main_info, ... NS_REQUIRES_NIL_TERMINATION {
NSString *to_local = NSLocalizedString(main_info, nil);
va_list arglist;
va_start(arglist, main_info);
id arg = va_arg(arglist, id);
if (arg) {
if ([to_local containsString:@"\n"]) {
NSRange range = [to_local rangeOfString:@"\n"];
NSInteger index = range.location;;
NSRange range_1 = NSMakeRange(0, index);
// 实例化可变属性的字符串对象
NSMutableAttributedString *attr_str = [[NSMutableAttributedString alloc] initWithString:to_local];
void(^add_Attribute)(id arg) = ^(id arg) {
if ([arg isKindOfClass:[UIColor class]]) {
[attr_str addAttributes:@{NSForegroundColorAttributeName: arg }
range:NSMakeRange(0, to_local.length)];
}
else if ([arg isKindOfClass:[NSNumber class]]) {
NSInteger main_font = [arg integerValue];
// 设置文字的颜色和文字的大小
[attr_str addAttributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:main_font]}
range:range_1];
NSRange range_2 = NSMakeRange((index + 1), to_local.length - (index + 1));
// 设置文字的颜色和文字的大小
[attr_str addAttributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:main_font * 0.7]}
range:range_2];
}
else {
}
};
add_Attribute(arg);
while ((arg = va_arg(arglist, id))) {
add_Attribute(arg);
}
va_end(arglist);
return attr_str;
}
else {
va_end(arglist);
return to_local;
}
}
else {
va_end(arglist);
return to_local;
}
}
id style_info = GCLocal(@"搜索中\nSearching", [UIColor whiteColor], @(35));
if ([style_info isKindOfClass:[NSAttributedString class]]) {
self.none_tv.attributedText = style_info;
}
else {
self.none_tv.text = style_info;
}