I want to parse simple HTML markup into a NSAttributedString
so that I can display formatted text on an UITextView
. I found this and that post where it should be easy to convert. That is what I've used:
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;
}
This is working so far, but now I want to change the font size, because the default one is very small.
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;
The code above does parse it correctly, but the font size isn't changed. I tried to use NSMutableAttributedString
, but it seems that it takes no NSData
as argument for parsing like the NSAttributedString
does. Perhaps it would be an option to combine multiple NSAttributedString
, but I don't know how. Another option would be to cast like this example:
NSMutableAttributedString attributedString = (NSMutableAttributedString) GetAttributedStringFromHtml (content);
attributedString.AddAttribute (UIStringAttributeKey.Font, UIFont.SystemFontOfSize (25), new NSRange (0, content.Length));
textView.AttributedText = attributedString;
but I get System.InvalidCastException
.
How can I change the font size of the UITextView
even if I use the HTML parsing?
Edit:
Now I tried to create my 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;
This does compile, the font size is bigger and also the HTML is parsed, but it ignorses the <strong>
for example. The text isn't bold, where it should be. It seems that the second attribute overwrites the first one ...
I tried a few things but none of them worked. So I'm already parsing the HTML why not use inline CSS syntax?
<p style='font-size:17px'><strong>I'm bold.</strong><br/>http://www.google.com</p>