I am rendering a textview with HTML content. I have taken some "div" tags and applied some CSS on them. I faced an issue while applying padding on "div" using a CSS class which is not reflecting on the div after rendering on the textview. I used the following method to convert HTML content string to an attributed string.
if let htmlData = htmlContent.dataUsingEncoding(NSUnicodeStringEncoding, allowLossyConversion: true) {
do {
return try NSMutableAttributedString(
data: htmlData,
options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
documentAttributes: nil)
}
catch let error as NSError {
printDebuggingMode("Couldn't translate \(htmlContent): \(error.localizedDescription) ")
}
}
I want to achieve something like this as attached below in the image in textView.
.padding {
padding-left: 20px;
}
The problem is that UITextView
does not support padding attributes inside HTML content. With that in mind you have two options here:
On one hand, use UIWebView
, as suggested in replies. You'll have same functionality as in an UITextView
, but you'll have to calculate the height of your text using something like this:
This method returns the height without considering insets of the UITextView
, you'll need to add those later.
func heightForText(text: String?, width: CGFloat) -> CGFloat {
//Get attributed text from string
let attributedText = text?.toHtmlTextWithAttributes()
if let attributedText = attributedText {
let rect = attributedText.boundingRectWithSize(
CGSizeMake(width, CGFloat.max),
options: [.UsesLineFragmentOrigin, .UsesFontLeading],
context: nil)
return rect.height
}
//Return any default height
return 100
}
Here is the String
extension which transforms text into NSAttributedString
.
extension String {
public func toHtmlTextWithAttributes() -> NSAttributedString? {
let encodedData = self.dataUsingEncoding(NSUTF8StringEncoding)
if let data = encodedData {
let paragrahpStyle = NSMutableParagraphStyle()
paragrahpStyle.lineBreakMode = .ByWordWrapping
let attributes: [String: NSObject] = [
NSParagraphStyleAttributeName: paragrahpStyle,
NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute: NSUTF8StringEncoding
]
return try! NSAttributedString(data: data, options: attributes, documentAttributes: nil)
}
return nil
}
}
Also the use of UITableViewAutomaticDimension
is not recommended, because in quite large lists it may lead to performance issues.
On the other hand, if you need to use UITextView
by all means, you can parse the html, extract the title and the paragraph and display them in two separated UITextView
. In that way you'll be able to adjust the insets of the second UITextView
like this:
textView.textContainerInset = UIEdgeInsetsMake(0, 20, 0, 0)
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