NSMutableAttributedString *titleAttriString = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@”¥200现金券”]];
[titleAttriString addAttribute:NSFontAttributeName
value:[UIFont systemFontOfSize:25]
range:NSMakeRange(0, titleAttriString.length - 3)];
[titleAttriString addAttribute:NSFontAttributeName
value:[UIFont systemFontOfSize:14]
range:NSMakeRange(titleAttriString.length - 3,3)];
[titleLb setAttributedText:titleAttriString];
注意:
NSMakeRange(文字的起始位置,文字长度)
换行的实现
如果想要计算NSAttributedString所要的size,就需要用到这个API:
CTFramesetterSuggestFrameSizeWithConstraints,用NSString的sizeWithFont算多行时会算不准的,因为在CoreText里,行间距也是你来控制的。
设置行间距和换行模式都是设置一个属性:kCTParagraphStyleAttributeName,这个属性里面又分为很多子
属性,其中就包括
kCTLineBreakByCharWrapping
kCTParagraphStyleSpecifierLineSpacingAdjustment
设置如下:
//————-取消注释,实现换行————-
CTParagraphStyleSetting lineBreakMode;
CTLineBreakMode lineBreak = kCTLineBreakByCharWrapping; //换行模式
lineBreakMode.spec = kCTParagraphStyleSpecifierLineBreakMode;
lineBreakMode.value = &lineBreak;
lineBreakMode.valueSize = sizeof(CTLineBreakMode);
//行间距
CTParagraphStyleSetting LineSpacing;
CGFloat spacing = 4.0; //指定间距
LineSpacing.spec = kCTParagraphStyleSpecifierLineSpacingAdjustment;
LineSpacing.value = &spacing;
LineSpacing.valueSize = sizeof(CGFloat);
CTParagraphStyleSetting settings[] = {lineBreakMode,LineSpacing};
CTParagraphStyleRef paragraphStyle = CTParagraphStyleCreate(settings, 2); //第二个参数为settings的长度
[attriString addAttribute:(NSString *)kCTParagraphStyleAttributeName
value:(id)paragraphStyle
range:NSMakeRange(0, attriString.length)];