AttributedString
為了便於添加新屬性,我們一般初始化 NSMutableAttributedString 類型的富文本。
NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:@"我是一個富文本"];
當然attrStr還有很多其他的初始化方法,比如initWithData之類的,可以望文生義,不在此贅述。
下面是為富文本增加各種屬性的方法,在這里先說明幾個數據類型的意義:
① NSMakeRange(X, Y) 從X位開始,長度為Y個字符/漢字的范圍。注意字符串的下標是從0開始的。
//修改字體 很顯然改字體 [attrStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:30.0f] range:NSMakeRange(4, 3)]; //顏色 //文字的顏色 形如:紅色的字 [attrStr addAttribute:NSForegroundColorAttributeName value:[UIColor orangeColor] range:NSMakeRange(0, attrStr.length)]; //文字背景顏色 形如:紅色背景的字 [attrStr addAttribute:NSBackgroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, attrStr.length)]; //下划線 下划線的字 [attrStr addAttribute:NSUnderlineStyleAttributeName value:@(NSUnderlineStyleSingle) range:NSMakeRange(4, 3)]; //刪除線 帶刪除線的字 //黑色刪除線 [attrStr addAttribute:NSStrikethroughStyleAttributeName value:@(NSUnderlinePatternSolid | NSUnderlineStyleSingle) range:NSMakeRange(4, 3)]; //也可以自定義刪除線的顏色 [attrStr addAttribute:NSStrikethroughColorAttributeName value:[UIColor redColor] range:NSMakeRange(4, 3)]; /* 調整到基准線的距離 用於 比如前面字體比后面的字體要大,但是需要小字體的內容垂直方向上居中 value為正向上偏,為負向下偏
*/ [attrStr addAttribute:NSBaselineOffsetAttributeName
value:@(10.0) //此處上移的距離可以根據 0.5*(大字體字號-小字體字號) 來大致推算
range:NSMakeRange(3, 2)];
//段落,行距等格式 //需要先建立一個格式的數據 NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init]; // 行間距 paragraphStyle.lineSpacing = 15; // 段落間距(以換行符為判斷段落的依據) paragraphStyle.paragraphSpacing = 30; // 段落縮進像素 paragraphStyle.firstLineHeadIndent = 40; // 整體縮進像素 paragraphStyle.headIndent = 15; // 對齊方式 paragraphStyle.alignment = NSTextAlignmentLeft;
//為富文本添加格式 [attrStr addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, attrStr.length)];
用富文本解析html文本
//html文本處理函數,輸入html文本內容 - (NSAttributedString *)attributedStringWithHTMLString:(NSString *)htmlString { //轉換參數 NSDictionary *options = @{ NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute :@(NSUTF8StringEncoding) }; //將html文本轉換為正常格式的文本 NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUnicodeStringEncoding] options:options documentAttributes:nil error:nil]; //以下三個設置其實不是必要的,只是為了讓解析出來的html文本更好看。 //設置段落格式 NSMutableParagraphStyle *para = [[NSMutableParagraphStyle alloc] init]; para.lineSpacing = 5; para.paragraphSpacing = 10; [attStr addAttribute:NSParagraphStyleAttributeName value:para range:NSMakeRange(0, attStr.length)]; //顏色 [attStr addAttribute:NSForegroundColorAttributeName value:HEXCOLOR(0x9b9b9b) range:NSMakeRange(0, attStr.length)]; //字體 [attStr addAttribute:NSFontAttributeName value:MFPFFONT_REGULAR(12) range:NSMakeRange(0, attStr.length)]; return attStr; }
