I am trying to load an HTML file via NSAttributedString to display it in a UITextView.
So, how can I apply CSS to the text view's content?
Since iOS 7 you can use NSAttributedString
with HTML syntax:
NSURL *htmlString = [[NSBundle mainBundle] URLForResource: @"string" withExtension:@"html"];
NSAttributedString *stringWithHTMLAttributes = [[NSAttributedString alloc] initWithFileURL:htmlString
options:@{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType}
documentAttributes:nil
error:nil];
textView.attributedText = stringWithHTMLAttributes; // attributedText field!
You have to add string.html to you project, and the content of the html can be like this:
<html>
<head>
<style type="text/css">
body {
font-size: 15px;
font-family: Avenir, Arial, sans-serif;
color: red;
}
</style>
</head>
<body>
<p>This is the text</p>
</body>
</html>
From what I could test, you can change: color, font-family, font-weight, font-size, text-align, and use <b>
, <strong>
, <i>
, <u>
, <sup>
, and <sub>
tags.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With