美文网首页
iOS-NSMutableAttributedString-调整

iOS-NSMutableAttributedString-调整

作者: QYCD | 来源:发表于2023-01-31 15:26 被阅读0次

    需要的效果:

    1. 配置文案拼接,中间使用"|"分割,最多两行,超出...代替
    2. 关键点在于NSBaselineOffsetAttributeName属性; 分割"|"明显靠下了,通过NSBaselineOffsetAttributeName向上调整了2个单位
    _configL = [[UILabel alloc] init];
    _configL.numberOfLines = 2;
    _configL.lineBreakMode = NSLineBreakByTruncatingTail;
    
    NSArray *configList = @[@"旗舰型", @"2.0TD-7DCT EVO", @"翠羽幻彩车漆", @"元气蓝双", @"21英寸多幅射线轮毂"];
    NSString *configStr = [NSString string];
    for (NSString *str in configList) {
        if (StrEmpty(configStr)) {
            configStr = [configStr stringByAppendingFormat:@"%@  |", str];
        } else {
            configStr = [configStr stringByAppendingFormat:@"  %@  |", str];
        }
    }
    if ([configStr hasSuffix:@"|"]) {
        configStr = [configStr substringToIndex:configStr.length - 1];
    }
    
    NSMutableParagraphStyle *paragraphStyle = [NSMutableParagraphStyle new];
    paragraphStyle.lineSpacing = 8;
    NSDictionary *attributes = @{
        NSFontAttributeName:FONT_Regular(Width_SIZEFIT(12)),
        NSForegroundColorAttributeName:RGB_HEX(0x7D7D7D),
        NSParagraphStyleAttributeName:paragraphStyle};
    
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:configStr attributes:attributes];
    for (int i = 0; i < configStr.length; i++) {
        NSString *colorStr = [configStr substringWithRange:NSMakeRange(i, 1)];
        if([colorStr isEqualToString:@"|"]) {
            [attributedString addAttribute:NSForegroundColorAttributeName value:RGB_HEX(0xC8C8C8) range:NSMakeRange(i, 1)];
            [attributedString addAttribute:NSFontAttributeName value:FONT_Regular(8) range:NSMakeRange(i, 1)];
            [attributedString addAttribute:NSBaselineOffsetAttributeName value:@2 range:NSMakeRange(i, 1)];
        }
    }
    _configL.attributedText = attributedString;
    

    实现效果:


    image.png

    相关文章

      网友评论

          本文标题:iOS-NSMutableAttributedString-调整

          本文链接:https://www.haomeiwen.com/subject/wdqbhdtx.html