Do I use NSAttributedString or UIWebView Swift

怎甘沉沦 提交于 2019-12-25 02:56:02

问题


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?


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/28866767/do-i-use-nsattributedstring-or-uiwebview-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!