iOS UILabel加載HTML文本

項目中有時候接口返回HTML格式的文本,客戶端顯示,第一反應用webView啊,可是返回的文本很少,使用耗能極大的webView得不償失啊,因此這時候才用UILabel或是UITextView加載HTML格式的文本。

具體測試代碼以下:html

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self.view addSubview:self.testLabel];
    [self loadHtmlTOLabel];
}

- (void)loadHtmlTOLabel {
    //返回的HTML文本
    NSString *htmlStr = @"Enter <a href=\"https://app-gearbest.com.trunk.s1.egomsl.com/my-coupon.html\" target=\"_blank\"><b>\"My Coupon\"</b></a> page to.3. Go to your 「My Coupon」 page to view your Coupon!<br>4. GearBest reserves the right to amend this activity. For any queries, please contact our Support Staff. (<a href=\"https://support.gearbest.com\" target=\"_blank\">https://support.gearbest.com</a>)";
    
    //富文本,兩種均可以
    NSDictionary *options = @{ NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute :@(NSUTF8StringEncoding) };
    NSData *data = [htmlStr dataUsingEncoding:NSUTF8StringEncoding];
    //或者
//    NSDictionary *option = @{NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType};
//    NSData *data = [htmlStr dataUsingEncoding:NSUnicodeStringEncoding];
    
    //設置富文本
    NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithData:data options:options documentAttributes:nil error:nil];
    //設置段落格式
    NSMutableParagraphStyle *para = [[NSMutableParagraphStyle alloc] init];
    para.lineSpacing = 7;
    para.paragraphSpacing = 10;
    [attStr addAttribute:NSParagraphStyleAttributeName value:para range:NSMakeRange(0, attStr.length)];
    self.testLabel.attributedText = attStr;
    
    //設置文本的Font沒有效果,默認12字號,這個只能服務器端控制嗎? 暫時沒有找到方法修改字號
    [attStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20] range:NSMakeRange(0, attStr.length)];
    //計算加載完成以後Label的frame
    CGSize size = [self.testLabel sizeThatFits:CGSizeMake(300, 1000)];
    //也能夠使用這個方法,對應好富文本字典
//    CGSize size = [self.testLabel.attributedText boundingRectWithSize:CGSizeMake(300, 1000) options:@{} context:nil];
    self.testLabel.frame = CGRectMake(50, 100, size.width, size.height);
}

#pragma mark setter and getter
- (UILabel *)testLabel {
    if (!_testLabel) {
        _testLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, 100, 300, 100)];
        _testLabel.textColor = [UIColor blackColor];
        _testLabel.backgroundColor = [UIColor whiteColor];
        _testLabel.textAlignment = NSTextAlignmentCenter;
        _testLabel.numberOfLines = 0;
        //怎麼設置字號都沒有效果
        _testLabel.font = [UIFont systemFontOfSize:20];
    }
    return _testLabel;
}

複製代碼

這裏要說明幾個問題:

1.加載HTML文本以後,能夠調整其顯示的段落格式。 2.可能不能設置字號UIFont,貌似只能是服務器端控制。知道的吧友還請告知一下,感激涕零。 3.能夠求出顯示完成以後控件的大小,富文本長度等信息。 4.當服務器返回的不是標準的HTML格式文本時,先進行一下轉化。web

//將 &lt 等相似的字符轉化爲HTML中的「<」等 
- (NSString *)htmlEntityDecode:(NSString *)string
{
    string = [string stringByReplacingOccurrencesOfString:@"&quot;" withString:@"\""];
    string = [string stringByReplacingOccurrencesOfString:@"&apos;" withString:@"'"];
    string = [string stringByReplacingOccurrencesOfString:@"&lt;" withString:@"<"];
    string = [string stringByReplacingOccurrencesOfString:@"&gt;" withString:@">"];
    string = [string stringByReplacingOccurrencesOfString:@"&amp;" withString:@"&"]; // Do this last so that, e.g. @"&amp;lt;" goes to @"&lt;" not @"<"

    return string;
}

複製代碼

5.還有一個可能會出現的問題。

當你加載完HTML顯示正常以後,在這個界面停留幾分鐘,可能會出現閃退,報錯**webView Thread**問題。可能會碰見,可能也不會,暫時不知道緣由。解決辦法:將加載HTML富文本放在線程裏bash

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            
            NSAttributedString *attributeStr = [[NSAttributedString alloc] initWithData:[htmlStr dataUsingEncoding:NSUnicodeStringEncoding] options:@{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType} documentAttributes:nil error:nil];
             dispatch_async(dispatch_get_main_queue(), ^{
                
                 self.testLabel.attributedText = attributeStr;
             });
        });
複製代碼

6.至於怎麼獲取跳轉連接等問題,能夠參考YYLabel。

反正我是沒有找到自動跳轉連接功能,只能本身篩選出來連接,進行跳轉。 有知道更好辦法的吧友,請告知下,O(∩_∩)O謝謝!服務器

相關文章
相關標籤/搜索