我使用 NSAttributedString 还是 UIWebView Swift [英] Do I use NSAttributedString or UIWebView Swift

查看:51
本文介绍了我使用 NSAttributedString 还是 UIWebView Swift的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据您从网站数据库中选择的业务,我得到了占用busDescriptio"的不同字符串.此字符串包含 html 标签、图像和链接.我被告知使用 NSAttributedString 而不是 UIWebView,因为 UIWebView 给了我各种各样的问题,例如图像位置错误、文本字体和文本颜色无法完全工作.我是 Swift 的新手,所以我无法真正理解 NSAttributedString 的工作原理.我能够去除 html 标签并保留字体,但这带走了图像、链接、ext.有了这个

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 

然后我将它加载到 UITextView

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)

我不喜欢这些工作的方式,所以这就是我想要做的.- 我想更改字体大小、字体颜色,并使用我的字符串 (busDescriptio) 接收图像.我是使用 UIWebView 来完成这项工作还是使用 NSAttributedString?如果是这样,我该怎么做?

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?

推荐答案

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

这篇关于我使用 NSAttributedString 还是 UIWebView Swift的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆