標籤:src lte 調用 bsp com get html tty 顯示
html代碼
圖1
樣式一:"<p><img src=\"/upload/image/20170609/1496978712941664.jpg\" title=\"1496978712941664.jpg\" alt=\"7.jpg\"/>測試內容資訊無錯</p>"樣式二:<h1 style=\"font-size: 32px; font-weight: bold; border-bottom: 2px solid rgb(204, 204, 204); padding: 0px 4px 0px 0px; text-align: left; margin: 0px 0px 10px;\">你好 <a href=\"https://baidu.com\" target=\"_self\" title=\"五六千可\">了的好萊塢去任何</a><img src=\"http://imgsrc.baidu.com/imgad/pic/item/caef76094b36acaf0accebde76d98d1001e99ce7.jpg\"/></h1><p><br/></p>
圖2
一、情景1:載入到UILabel上面(轉換成富文本即可)
//1.將字串轉化為標準HTML字串 NSString *str1 = [self htmlEntityDecode:htmlString];//2.將HTML字串轉換為attributeString NSAttributedString * attributeStr = [self attributedStringWithHTMLString:str1]; //3.使用label載入html字串並將label添加到view上 self.label.attributedText = attributeStr; [self.label setFrame:CGRectMake(100,100,200,300)]; [self.view addSubview:self.label];//------html 轉換成字串//將 < 等類似的字元轉化為HTML中的“<”等 - (NSString *)htmlEntityDecode:(NSString *)string{ string = [string stringByReplacingOccurrencesOfString:@""" withString:@"\""]; string = [string stringByReplacingOccurrencesOfString:@"‘" withString:@"‘"]; string = [string stringByReplacingOccurrencesOfString:@"<" withString:@"<"]; string = [string stringByReplacingOccurrencesOfString:@">" withString:@">"]; string = [string stringByReplacingOccurrencesOfString:@"&" withString:@"&"]; // Do this last so that, e.g. @"<" goes to @"<" not @"<" return string;}//------ 將html轉換成富文本//將HTML字串轉化為NSAttributedString富文本字串- (NSAttributedString *)attributedStringWithHTMLString:(NSString *)htmlString{ NSDictionary *options = @{ NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute :@(NSUTF8StringEncoding) }; NSData *data = [htmlString dataUsingEncoding:NSUTF8StringEncoding]; return [[NSAttributedString alloc] initWithData:data options:options documentAttributes:nil error:nil];}//圖2 中的樣式2 可以會出現顯示空白,可以通過去除html標籤來處理//去掉 HTML 字串中的標籤- (NSString *)filterHTML:(NSString *)html{ NSScanner * scanner = [NSScanner scannerWithString:html]; NSString * text = nil; while([scanner isAtEnd]==NO) { //找到標籤的起始位置 [scanner scanUpToString:@"<" intoString:nil]; //找到標籤的結束位置 [scanner scanUpToString:@">" intoString:&text]; //替換字元 html = [html stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@>",text] withString:@""]; } return html;}
二、情景2:載入到UIWebView上面(替換html中部分的字元)
//1.將字串轉化為標準HTML字串,(此處的字串不是標準的標籤的HTML字串,將字串轉換成標準的HTML字串,這樣才可以進行HTML字串的載入) NSString *str1 = [self htmlEntityDecode:htmlString];//調用情景1的方法 //2.UIWebView 載入HTML字串 UIWebView * webView = [[UIWebView alloc] initWithFrame:CGRectMake(20, 150, self.view.frame.size.width-20, 400)]; [webView loadHTMLString:str1 baseURL:nil]; [self.view addSubview:webView];
iOS開發網路篇 —— OC載入HTML代碼