0

我正在創建一個應該顯示字符串列表的應用程序,該字符串從服務器返回並且可以是html或不是。 我目前正在UILabel中設置文本。要做到這一點,我使用下面的檢查一個NSString是否是一個html字符串?

NSMutableAttributedString *attributedTitleString = [[NSMutableAttributedString alloc] initWithData:[title dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil]; 
cell.label.attributedText =attributedTitleString; 

當文本是一個html,一切都完美地工作,因爲字體和比對的HTML中返回。如果文本是普通文本,則會發生此問題。字體,文字對齊,文字大小和其他不再受到尊重。

那麼如何檢查文本是否是html字符串呢? 我將使用在普通文本的情況如下:

cell.label.text =title; 

我曾嘗試在論壇上搜索,但還是沒有得到我的問題的任何答案。

+0

你是什麼意思,字體pp。不再受到尊重?如果它是純文本,則不存在這樣的屬性。 –

+0

我的意思是在創建標籤時,我將ex和settextalignment中心的字體設置爲20。但是,當我設置cell.label.attributedText = attributedTitleString(從純文本),字體是如此之小,左對齊 –

+0

我認爲這是不可能的。你只能檢查你的html字符串是否包含html標籤。 (以正則表達式爲例) – Pipiks

回答

1

這是工作正常,你需要把:

cell.label. attributedText = title;櫃面普通文本的了。

由於它工作正常。運行下面的代碼。

//如果HTML文本

NSString *htmlstr = `@"This is <font color='red'>simple</font>"`; 

NSMutableAttributedString *attributedTitleString = [[NSMutableAttributedString alloc] initWithData:[htmlstr dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil]; 

textField.attributedText =attributedTitleString; 

textField.font = [UIFont fontWithName:@"vardana" size:20.0]; 

//如果普通文本。

NSString *normalStr = @"This is Renuka"; 

NSMutableAttributedString *NorAttributedTitleString = [[NSMutableAttributedString alloc] initWithData:[normalStr dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil]; 

textField.attributedText = NorAttributedTitleString; 

textField.font = [UIFont fontWithName:@"vardana" size:20.0]; 
+0

我不想總是設置HTML文本的情況下的屬性文本後設置字體,因爲這將覆蓋從HTML返回的字體 –

+0

我沒有得到你,你只想改變正常文本的字體? – Ren

+0

只適用於普通文本,因爲在字符串是html的情況下,字體會自動設置在HTML內 –

1

您可以檢查您的字符串包含HTML標記:

// iOS8上+

NSString *string = @"<TAG>bla bla bla html</TAG>"; 

if ([string containsString:@"<TAG"]) { 
    NSLog(@"html string"); 
} else { 
    NSLog(@"no html string"); 
} 

// iOS7 +

NSString *string = @"<TAG>bla bla bla html</TAG>"; 

if ([string rangeOfString:@"<TAG"].location != NSNotFound) { 
    NSLog(@"html string"); 
} else { 
    NSLog(@"no html string"); 
} 
相關問題