第一篇博客!
--------------------------------------------------
需求:在同一个label上显示 两种规格的字体。
例如:把字符串是320M(100M)中的M字号变小. 如图 →
--------------------------------------------------
解决方法:
给UILabel设置文本时候,使用UILabel的 attributedText 属性 代替 text属性
--------------------------------------------------
例子:
调用:
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 50)];
[label setFontOfString:@“320M(100M)” subString:@”M” desFontSize:20];
UILabel的Category:
@implementation UILabel (AppAdditions)
– (void) setFontOfString:(NSString )fullString subString:(NSString )subString desFontSize:(NSInteger)fontSize
{
if (fullString == nil) {
self.attributedText = [[NSMutableAttributedString alloc] initWithString:@”“];
return ;
}
NSString *replaceString = @”“;
for (int i = 0; i < subString.length; i++) {
replaceString = [replaceString stringByAppendingString:@” “];
}
NSString *copyStr = [NSMutableString stringWithString:fullString];
NSMutableArray *rangeLocArray = [NSMutableArray array];
while ([copyStr rangeOfString:subString].location != NSNotFound)
{
NSRange range = [copyStr rangeOfString:subString];
[rangeLocArray addObject:@(range.location)];
copyStr = [copyStr stringByReplacingCharactersInRange:NSMakeRange(range.location, range.length) withString:replaceString];
}
NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:fullString];
for (NSNumber *rangeLoc in rangeLocArray) {
UIFont *baseFont = [UIFont systemFontOfSize:fontSize];
NSRange range = NSMakeRange(rangeLoc.integerValue,subString.length);
[attrString addAttribute:NSBaselineOffsetAttributeName value:@(0.0f) range:range];
[attrString addAttribute:NSFontAttributeName value:baseFont range:range];
}
self.attributedText = attrString;
}
@end
--------------------------------------------------
第一次写博客。希望可以和大家共同进步!(布局不好看,不过办公室网太卡了,之后再研究markdown页面的布局,先来一发再说!)