CSS padding on HTML text attribute for textView not working

I am presenting a textview with HTML content. I took some “div” tags and applied some CSS to them. I ran into a problem when applying the add-on to a “div” using a CSS class that doesn't reflect on the div after rendering in a textview. I used the following method to convert a string of HTML content to an attribute 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 shown below in an image in a textView.

 .padding { padding-left: 20px; } 
+6
source share
1 answer

The problem is that UITextView does not support fill attributes inside HTML content. With this in mind, you have two options:

For one thing, use UIWebView as suggested in the answers. You will have the same functionality as in the UITextView , but you will need to calculate the height of the text using something like this:

This method returns the height excluding UITextView attachments, you will need to add them 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 a String extension that converts text to 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 not recommended, as in fairly large lists this can lead to performance problems.

On the other hand, if you need to use UITextView all ways, you can UITextView html, extract the heading and paragraph, and display them in two separate UITextView . This way you can customize the inserts of the second UITextView as follows:

 textView.textContainerInset = UIEdgeInsetsMake(0, 20, 0, 0) 
0
source

All Articles