iOS Swift UITextView HTML text example

iOS Swift UITextView HTML text example


import UIKit

class ViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationItem.title = "Main View"
        
        addUITextViews()
       
    }
    
    func addUITextViews(){
        
        //lauout for the View
        let myTextView = UITextView()
        myTextView.translatesAutoresizingMaskIntoConstraints = false
        self.view.addSubview(myTextView)
        
        let views = [
            "view" : view,
            "textView" : myTextView
            ]
        
        var allConstraints: [NSLayoutConstraint] = []
        allConstraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|-[textView]-|",
            options: [], metrics: nil, views: views as [String : Any])
        allConstraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|-[textView]-|",
                            options: [], metrics: nil, views: views as [String : Any])
        NSLayoutConstraint.activate(allConstraints)
        
        
        // Some HTML text
        let htmlString = "<font size='24' color='green'>There is some <b>bold</b> text!</font><br/>" +
                         "<font size='24'>Next line....</font>"
        var attributedString: NSAttributedString? = nil
        if let data = htmlString.data(using: .utf8) {
            attributedString = try? NSMutableAttributedString(data: data,
                                            options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue], documentAttributes: nil)
        }
        
        // add attributed String
        myTextView.attributedText = attributedString
        
       
    }
    
    
}

No comments:

Post a Comment

NO JUNK, Please try to keep this clean and related to the topic at hand.
Comments are for users to ask questions, collaborate or improve on existing.