效果图:
有关 iOS 字符串上下标 (二)点击打开链接
主要代码:继承于UILabel
PollutantFormatlabel.h
#import <UIKit/UIKit.h>
IB_DESIGNABLE
@interface PollutantFormatlabel : UILabel
+(void)PollutantFormatLabel:(UILabel *)label labelValue:(NSString *)labelValue;
@end
PollutantFormatlabel.m
#import "PollutantFormatlabel.h"
#import <CoreText/CoreText.h>
#import "ValueLabel.h"
@interface PollutantFormatlabel ()
@property(nonatomic,strong)NSDictionary *dic;
@end
@implementation PollutantFormatlabel
/**
* scripting 1-上标 -1-下标
* loc 从哪个位置开始
* len 需要上下标的长度
*/
-(NSDictionary *)dic {
if (!_dic) {
_dic = @{@"μg/m3":@{@"scripting":@1,@"loc":@4,@"len":@1},
@"mg/m3":@{@"scripting":@1,@"loc":@4,@"len":@1},
@"PM10": @{@"scripting":@(-1),@"loc":@2,@"len":@2},
@"PM2.5":@{@"scripting":@(-1),@"loc":@2,@"len":@3},
@"O3": @{@"scripting":@(-1),@"loc":@1,@"len":@1},
@"O3_8H":@{@"scripting":@(-1),@"loc":@1,@"len":@1},
@"SO2": @{@"scripting":@(-1),@"loc":@2,@"len":@1},
@"NO2": @{@"scripting":@(-1),@"loc":@2,@"len":@1},
@"NOX": @{@"scripting":@(-1),@"loc":@2,@"len":@1},
@"NOx": @{@"scripting":@(-1),@"loc":@2,@"len":@1},
};
}
return _dic;
}
-(void)drawTextInRect:(CGRect)rect {
[PollutantFormatlabel PollutantFormatLabel:self labelValue:self.text];
[super drawTextInRect:rect];
}
+(void)PollutantFormatLabel:(UILabel *)label labelValue:(NSString *)labelValue {
PollutantFormatlabel *p = [PollutantFormatlabel new];
float size = label.font.pointSize;
UIFont *smallFont = [UIFont systemFontOfSize:size/1.7];
NSMutableAttributedString *attString = [[NSMutableAttributedString alloc] initWithString:labelValue];
[attString beginEditing];
for (NSString *key in p.dic.allKeys) {
NSRange strRange = [labelValue rangeOfString:key];
if (strRange.location != NSNotFound) {
NSDictionary *dic = p.dic[key];
NSInteger loc = [dic[@"loc"] integerValue]+strRange.location;
NSInteger len = [dic[@"len"] integerValue];
NSRange range = NSMakeRange(loc,len);
NSNumber *scripting = dic[@"scripting"];
[attString addAttribute:NSFontAttributeName value:(smallFont) range:range];
[attString addAttribute:(NSString*)kCTSuperscriptAttributeName value:scripting range:range];
}
}
[attString endEditing];
label.text = labelValue;
label.attributedText = attString;
}
@end
使用:
我的业余技术微信公众号:YKJGZH,欢迎大家进入