0
votes

I'm getting different strings that occupy "busDescriptio" depending on what business you choose from a website database. This string contains html tags, images, and links. I was told to use NSAttributedString instead of UIWebView because UIWebView was giving me all sorts of problems such as images in wrong place, text font, and text color wouldn't fully work. I'm new to Swift so I cant really wrap my head around how NSAttributedString works. I was able to strip out the html tags and keep the font but that took away images, links, ext. with this

let encodedString = "\(busDescriptio)"
            let encodedData = encodedString.dataUsingEncoding(NSUTF8StringEncoding)!
            let attributedOptions = [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType]
            let attributedString = NSAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil, error: nil)

            let decodedString = attributedString?.string 

and I loaded it into a UITextView

// Create UITextView
            var textView = UITextView(frame: CGRectMake(0, 95.0, screenWidth-10, 300.0))
            textView.text = decodedString
            textView.font = UIFont.preferredFontForTextStyle(UIFontTextStyleBody)

            border.addSubview(textView)

I dont like how any of this works so here is what I'm trying to do. - I wanting to change the font size, font color, and take in images with my string(busDescriptio). Do I use UIWebView to get this done or NSAttributedString? If so how can I do this?

2

2 Answers

3
votes
extension String {
    var html2AttStr:NSAttributedString {
        return NSAttributedString(data: dataUsingEncoding(NSUTF8StringEncoding)!, options:[NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: NSUTF8StringEncoding], documentAttributes: nil, error: nil)!
    }
}

let yourAttributedText = "<style type=\"text/css\">#red{color:#F00}#green{color:#0F0}#blue{color: #00F; font-weight: Bold; font-size: 32}</style><span id=\"red\" >Red,</span><span id=\"green\" > Green </span><span id=\"blue\">and Blue</span>".html2AttStr

textView.attributedText = yourAttributedText
1
votes

An attributed string is a string with attributes.

The string property returns the string without attributes.

You're building a string with attributes, throwing away all the attributes, then handing just the text to the text view.

Set attributedString to the text view's attributedText property to give it the attributes.