[英]Show html and css files
我有index.html
和style.css
文件。 在這些文件中,我只有文本。 我想在我的textView
顯示此文本。 如果我使用此代碼,我將顯示文件中的文本:
class ReadViewController: UIViewController {
@IBOutlet weak var textView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
do {
guard let filePath = Bundle.main.path(forResource: "index", ofType: "html")
else {
print ("File reading error")
return
}
let contents = try String(contentsOfFile: filePath, encoding: .utf8)
textView.attributedText = contents.htmlToAttributedString
}
catch {
print ("File HTML error")
}
}
}
extension String {
var htmlToAttributedString: NSAttributedString? {
guard let data = data(using: .utf8) else { return nil }
do {
return try NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding:String.Encoding.utf8.rawValue], documentAttributes: nil)
} catch {
return nil
}
}
var htmlToString: String {
return htmlToAttributedString?.string ?? ""
}
}
但在這種情況下,我的文本顯示時沒有粗體和其他樣式設置。 如何解決? 如何添加style.css
文件?
嘗試在您的代碼中添加內聯css。 下面的代碼應該可以幫助您入門:
let myFont = UIFont.systemFont(ofSize: 15)
let myHtmlText = "Html content goes here.."
let modifiedFont = String("<span style=\"font-family: \(myFont.fontName); font-size: \(myFont.pointSize); color:rgb(255,255,255);\">\(myHtmlText)</span>")
guard let data = modifiedFont.data(using: .utf8) else {
return
}
do {
textView.attributedText = try NSAttributedString(data: data,
options: [.documentType: NSAttributedString.DocumentType.html,
.characterEncoding:String.Encoding.utf8.rawValue],
documentAttributes: nil)
} catch {
// handle error
}
如果文件大小較小,請嘗試將 html 文件轉換為多行字符串,如上面的答案所述
您還可以使用如下擴展名:
extension NSAttributedString {
static func bolded(originalText:String, wordsToBold:[String], color:UIColor, font:UIFont, fontBold:UIFont? = nil) -> NSAttributedString {
let fontBoldTemp = fontBold ?? UIFont.appFont_Bold(fontSize: font.pointSize)
let attr = NSMutableAttributedString(string: originalText)
attr.addAttributes([NSAttributedString.Key.font : font,
NSAttributedString.Key.foregroundColor : color], range: NSRange(location: 0, length: originalText.count))
for eachWord in wordsToBold {
attr.addAttributes([NSAttributedString.Key.font : fontBoldTemp,
NSAttributedString.Key.foregroundColor : color], range: (originalText as NSString).range(of: eachWord))
}
return attr
}
}
然后使用它如下:
textView.attributedText = NSAttributedString.bolded(originalText: "This is sample text Bold1 and another Bold2",
wordsToBold: ["Bold1", "Bold2"],
color: UIColor.red,
font: UIFont.systemFont(ofSize: 13))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.