首页 > 技术文章 > iOS NSString 文本不同的颜色 标题+文本字体大小 行间距/删除不需要的字符 /以及自适应高度

xujiahui 2017-04-11 16:21 原文

#import <Foundation/Foundation.h>

@interface TextsForRow : NSObject

@property(nonatomic,copy)NSString * string;


/**
 文本包含: 标题+内容。 使用前设置内容的颜色
 作用:标题颜色 标题+文本字体大小 行间距(10)删除不需要的字符  以及自适应高度


 @param stringTitle title文本
 @param colorTitle title颜色
 @param stringText 内容text
 @return 返回数组3个。 1 返回的 NSMutableAttributedString * strAttebute;;2返回的 宽度0.2f的string,使用时转化 3:高度
 */
+(NSArray *)TextsForRowWithStringTitle:(NSString*)stringTitle ColorWith:(UIColor*)colorTitle textWithStringText:(NSString*)stringText;
@end

 

#import "TextsForRow.h"

@implementation TextsForRow

+(NSArray *)TextsForRowWithStringTitle:(NSString*)stringTitle ColorWith:(UIColor*)colorTitle textWithStringText:(NSString*)stringText{
    
    //title+text
    NSString * str1 =[NSString stringWithFormat:@"%@%@",stringTitle,stringText];
    
    //删除不需要的个别字符
    NSString * str = [str1  stringByReplacingOccurrencesOfString:@"<DIV>" withString:@""];
    str = [str stringByReplacingOccurrencesOfString:@"</DIV>" withString:@""];
    str = [str stringByReplacingOccurrencesOfString:@"<BR>" withString:@""];
    str = [str stringByReplacingOccurrencesOfString:@"</BR>" withString:@""];
    
    //删除讨厌的字符
    NSRegularExpression * regu2 =[NSRegularExpression regularExpressionWithPattern:@"(?:<|</|>|&nbsp;)" options:NSRegularExpressionCaseInsensitive error:nil];
    NSString *string3 = [regu2 stringByReplacingMatchesInString:str options:NSMatchingReportProgress range:NSMakeRange(0, str.length) withTemplate:@""];
    
    //去掉左右两边的空格
    NSString * kongge = [string3 stringByReplacingOccurrencesOfString:@" " withString:@""];

    //去掉左右两边的空格
    NSString * string = [kongge stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    
    
    NSMutableAttributedString * strAttebute = [[NSMutableAttributedString alloc] initWithString:string ];
    //设置title颜色
    [strAttebute addAttribute:NSForegroundColorAttributeName value:colorTitle range:NSMakeRange(0, stringTitle.length)]
    ;
    //行间距
    NSMutableParagraphStyle * paragraphStyle = [[NSMutableParagraphStyle alloc]init];
    [paragraphStyle setLineSpacing:IPHONEHIGHT(10)];
    [strAttebute addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, string.length)];
    
    //自定义大小
    CGSize contentSize = [string  boundingRectWithSize:CGSizeMake(ScreenWidth-IPHONEWIDTH(56),MAXFLOAT ) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:IPHONEWIDTH(30)]} context:NULL].size;
    
    CGFloat height = contentSize.height;

    //进行返回
    NSArray * array =@[strAttebute,[NSString stringWithFormat:@"%0.2f",contentSize.width],[NSString stringWithFormat:@"%0.2f",height]];
    
    return array;

}



@end

 

推荐阅读