(轉)解決NSMutableAttributedString富文本,不一樣文字大小水平軸對齊問題(默認底部對齊)

iOS晉級技術文章,請關注 hehuoya.com 合夥呀spa

默認是底部對齊,其實對的也不齊,code

目標效果: 
這裏寫圖片描述blog

代碼:圖片

這裏寫圖片描述

NSBaselineOffsetAttributeName

基線偏移量: 
調整: NSBaselineOffsetAttributeName的值得大小,就能夠獲得不一樣的對齊位置it

CGFloat fontRatio = 0.16;//基線偏移比率
  • 1

這裏寫圖片描述

CGFloat fontRatio = 0.66;//基線偏移比率
  • 1

這裏寫圖片描述

- (void)viewDidLoad { [super viewDidLoad]; self.title = @"富文本"; NSString *text = @"(2) 3 : 2 (1)"; NSInteger fontSize1 = 30; NSInteger fontSize2 = 16; CGFloat fontRatio = 0.66;//基線偏移比率 UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(150, 200, 150, 40)]; label.text = text; NSMutableAttributedString *attributedStringM = [[NSMutableAttributedString alloc] initWithString:text]; [attributedStringM addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:fontSize2] range:NSMakeRange(0, 3)]; [attributedStringM addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, 3)]; [attributedStringM addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:fontSize1] range:NSMakeRange(3, text.length - 6)]; [attributedStringM addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(3, text.length - 6)]; [attributedStringM addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:fontSize2] range:NSMakeRange(text.length - 3, 3)]; [attributedStringM addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(text.length - 3, 3)]; //不一樣大小的文字水平中部對齊(默認是底部對齊) [attributedStringM addAttribute:NSBaselineOffsetAttributeName value:@(fontRatio * (fontSize1 - fontSize2)) range:NSMakeRange(0, 3)]; [attributedStringM addAttribute:NSBaselineOffsetAttributeName value:@(fontRatio * (fontSize1 - fontSize2)) range:NSMakeRange(text.length - 3, 3)]; label.attributedText = attributedStringM; [self.view addSubview:label]; }
相關文章
相關標籤/搜索