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"); 
} 
相关问题