iOS 字符串上下标(一)

效果图:


有关 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,欢迎大家进入

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值