2015-10-23 19 views
1

我有一個UILabel。我想設置一個字符串,其中還包含一些HTML標籤。該字符串是:如何在UILabel上顯示HTML字符串

NSString *str = @"<p>Hey you. My <b>name </b> is <h1> Joe </h1></p>"; 

我怎麼能在UILabel

NSAttributedString * attrStr = [[NSAttributedString alloc] initWithData:[str dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil]; 



    mylabel.attributedText=attrStr; 

上面的代碼並不顯示任何內容顯示這一點。

+0

http://stackoverflow.com/questions/4789447/write-html-content-to-nsstring-and-display-on-iphone。希望對你有幫助。 – Meera

+0

不顯示任何東西? 'attrStr'無?使用'error'參數怎麼樣?是'myLabel'零? – Larme

+0

如果'UILabel'在你的情況下不起作用,那麼你爲什麼不使用爲它製作的'UIWebView'?只需禁用滾動。 – TheTiger

回答

4

對於iOS7或以上,你可以這樣做:

NSString * htmlString = @" <p><b>Hey</b> you. My <b>name </b> is <h1> Joe </h1></p> "; 
    NSAttributedString * attrStr = [[NSAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil]; 


UILabel * myLabel = [UILabel alloc] init]; 
myLabel.attributedText = attrStr; 

它的工作原理

+0

http://stackoverflow.com/questions/上有類似的答案19946251/how-to-show-an-html-string-on-a-uilabel-in-ios但是,它並不工作 – Illep

+0

我最近在ios 8.4上測試它,然後發佈評論,如果你想屏幕截圖然後檢查它下面鏈接 https://www.dropbox.com/s/jfu029l3g7z64cm/Screen%20Shot%202015-10-23%20at%205.08.54%20pm.png?dl=0 – Mahesh

+0

我沒有測試與uilabel,我確定它確實適用於UITextView – kokos8998

2

你應該使用下面的代碼。它幫助你! Apple爲NSAttributedString提供了文檔和鏈接。

https://developer.apple.com/documentation/foundation/nsattributedstring/1524613-initwithdata

NSString * htmlString = @"You added a note - in <a href='http://localhost:80/ABC/phase2/public/users/Test/notes/5'>hfgh</a>"; 
NSAttributedString * attrStr = [[NSAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil]; 
myLabel.attributedText = attrStr; 
+0

請同時描述您的解決方案,而不只是輸入代碼。 –