将简单HTML解析为NSAttributedString后,设置字体大小不起作用

时间:2015-02-04 14:54:43

标签: c# ios xamarin.ios xamarin nsattributedstring

我想将简单的HTML标记解析为NSAttributedString,以便我可以在UITextView上显示格式化文本。我发现thisthat的帖子应该很容易转换。这就是我用过的:

public static NSAttributedString GetAttributedStringFromHtml(string html)
{
    NSError error = null;
    NSAttributedString attributedString = new NSAttributedString (NSData.FromString(html), 
        new NSAttributedStringDocumentAttributes{ DocumentType = NSDocumentType.HTML, StringEncoding = NSStringEncoding.UTF8 }, 
        ref error);
    return attributedString;
}

到目前为止这是有效的,但现在我想更改字体大小,因为默认字体非常小。

string content = "<strong>I'm strong.</strong><br/>http://www.google.com";

UITextView textView = new UITextView ();
textView.Editable = false;
textView.Font = UIFont.SystemFontOfSize (25);
textView.Text = content;
textView.AttributedText = GetAttributedStringFromHtml (content);
textView.DataDetectorTypes = UIDataDetectorType.Link;
textView.Selectable = true;

上面的代码确实解析了它,但字体大小没有改变。我尝试使用NSMutableAttributedString,但似乎没有NSData作为解析的参数,就像NSAttributedString那样。也许结合多个NSAttributedString是一种选择,但我不知道如何。另一种选择是像这样的例子:

NSMutableAttributedString attributedString = (NSMutableAttributedString) GetAttributedStringFromHtml (content);
attributedString.AddAttribute (UIStringAttributeKey.Font, UIFont.SystemFontOfSize (25), new NSRange (0, content.Length));
textView.AttributedText = attributedString;

但我得到System.InvalidCastException

即使我使用HTML解析,如何更改UITextView的字体大小?

修改

现在我尝试创建NSMutableAttributedString

NSAttributedString parsedString = GetAttributedStringFromHtml (content);
NSMutableAttributedString attributedString = new NSMutableAttributedString (parsedString);
attributedString.AddAttribute (UIStringAttributeKey.Font, UIFont.SystemFontOfSize (17), new NSRange (0, attributedString.Length));
textView.AttributedText = attributedString;

这会编译,字体大小更大并且HTML也会被解析,但它会忽略<strong>。文字不是粗体,它应该在哪里。看来第二个属性会覆盖第一个属性......

1 个答案:

答案 0 :(得分:1)

我尝试了一些东西,但没有一个能奏效。所以我已经解析了为什么不使用内联CSS语法的HTML?

<p style='font-size:17px'><strong>I'm bold.</strong><br/>http://www.google.com</p>