當后台返回的json數據里有h5字符串該如何顯示


 

有時候一些數據是需要動態顯示,並且需要換行,但客戶端並不知道這些數據該在哪里換行,

並按照后台編輯格式來顯示,於是后台直接返回的后台編輯的h5字符串,但數據已經經過json

解析過了,再去通過專門解析h5的第三方去解析瞬間感覺頭大,於是我去百度了一下如何顯示

后台返回的h5字符串,有兩個方法,一種是label的attributedText,還一種是webView。

label的寫法:

  NSAttributedString * attrStr = [[NSAttributedString alloc] initWithData:

  [htmlString dataUsingEncoding:NSUnicodeStringEncoding] options:

  @{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];  

  UILabel * myLabel = [[UILabel alloc] initWithFrame:self.view.bounds];  

  myLabel.attributedText = attrStr; 

現在問題來,內容可以顯示,但達不到我要的效果,首先不知道label要設置多高,也有代碼:

計算attrStr的大小:
  CGSize size = [attrStr boundingRectWithSize:CGSizeMake(label.frame.size.width, MAXFLOAT) options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin |         NSStringDrawingUsesFontLeading context:nil].size; 

如果計算不准就用 [myLabel sizeToFit] ;

如果內容超出界面咋辦,放到scrollview里,好麻煩。於是我選擇了webView,因為里面本身就可以滑,也不用自己計算高度。

問題又來了,是用WKWebView還是UIWebView,一開始我使用了WKWebView,我以為越新的api功能更全更好用,但我錯了,顯示出來

大小完全不同,和螞蟻差不多,很失望,后面經過詢問使用UIWebView才是正解,瞬間打臉。

#import <WebKit/WebKit.h>

@property(nonatomic,strong)UIWebView * htmlWebV;

- (UIWebView *)htmlWebV

{

    if(_htmlWebV == nil)

    {

        _htmlWebV = [[UIWebView alloc] initWithFrame:CGRectMake(0, 100, 300, 200)];

        _htmlWebV.scrollView.bounces = NO

        _htmlWebV.scrollView.showsHorizontalScrollIndicator = NO;

        _htmlWebV.scrollView.backgroundColor = [UIColor whiteColor];

    }

    return _htmlWebV;

}

- (void)updateHtmlStr:(NSString *)htmlStr

{

    if(htmlStr.length > 0)

    {

        [_htmlWebV loadHTMLString:htmlStr baseURL:nil];

    }

}

[self.view addSubview:self.htmlWebV];

拿到數據之后,調用[self updateHtmlStr:htmlStr];


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM