Skip to content

Instantly share code, notes, and snippets.

@adrianstevens
Created January 20, 2015 20:09
Show Gist options
  • Save adrianstevens/933d66faaea83e165f5f to your computer and use it in GitHub Desktop.
Save adrianstevens/933d66faaea83e165f5f to your computer and use it in GitHub Desktop.
Xamarin IOS C# NSAttributedString example
/// http://forums.xamarin.com/discussion/18460/uitextview-and-html
/// <summary>
/// Gets the attributed string from html-string.
/// </summary>
/// <returns>The attributed string from html.</returns>
/// <param name="html">Html.</param>
public static NSAttributedString GetAttributedStringFromHtml(string html)
{
NSError error = null;
var htmlString = new NSAttributedString (NSUrl.FromString(html),
new NSAttributedStringDocumentAttributes{ DocumentType = NSDocumentType.HTML },
ref error);
return htmlString;
}
/// <summary>
/// Get attributed String from an URL-object
/// </summary>
/// <returns>The attributed string from html.</returns>
/// <param name="html">Html.</param>
public static NSAttributedString GetAttributedStringFromHtml(NSUrl html)
{
NSAttributedStringDocumentAttributes importParams = new NSAttributedStringDocumentAttributes();
importParams.DocumentType = NSDocumentType.HTML;
NSError error = null;
//NSDictionary dict = new NSDictionary ();
var attrString = new NSAttributedString (html, ref error);
return attrString;
}
/// <summary>
/// Gets the HTML from attributed string.
/// </summary>
/// <returns>The HTML from attributed string.</returns>
/// <param name="attributedString">Attributed string.</param>
public static NSString GetHTML(NSAttributedString attributedString)
{
var exportParams = new NSAttributedStringDocumentAttributes();
exportParams.DocumentType = NSDocumentType.HTML ;
NSError err = null;
NSData htmlData = attributedString.GetDataFromRange (new NSRange(0, attributedString.Length),
exportParams, ref err);
var retString = new NSString (htmlData, NSStringEncoding.UTF8);
return retString;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment