我在属性中使用了相同的字体:,它给出了以上错误
do {
let myAttribute = [ NSAttributedStringKey.font: UIFont(name: "Chalkduster", size: 18.0)! ]
let attrStr = try NSAttributedString(data: ("Some String HTML".data(using: String.Encoding.unicode, allowLossyConversion: false)!)!,options: [.documentType: NSAttributedString.DocumentType.html,
.characterEncoding: String.Encoding.utf8.rawValue],
documentAttributes: nil,attributes: myAttribute)
self.NoAccessMessage.font = UIFont(name: "Arial", size: 16.0)
self.NoAccessMessage.attributedText = attrStr
} catch let error {
}
请检查是否需要任何帮助
答案 0 :(得分:2)
您正在组合两种不同的东西。您可以 将属性应用于字符串或读取一些HTML。两者都不是。
也许你是这个意思:
let myAttribute = [ NSAttributedStringKey.font: UIFont(name: "Chalkduster", size: 18.0)! ]
let attrStr = NSAttributedString(string: "howdy there", attributes: myAttribute)
或者也许你是这个意思:
let html = "<p>howdy <b>there</b></p>"
let htmldata = html.data(using: .utf8)
let attrStr = try NSAttributedString(data: htmldata!, options: [.documentType : NSAttributedString.DocumentType.html], documentAttributes: nil)
下定决心。
答案 1 :(得分:0)
使用此方法,您可以同时应用(Swift 4代码)
@IBOutlet weak var txtWv1: UITextView!
@IBOutlet weak var txtWv2: UITextView!
class SampleViewController: UIViewController{
override func viewDidLoad() {
super.viewDidLoad()
// Sample HTML Text
let html = "<ul> <li>Lorem ipsum dolor sit amet, consectetuer
adipiscing elit.</li> <li>Aliquam tincidunt mauris
eurisus.</li> <li>Vestibulum auctor dapibus neque.</li>
</ul>"
do {
let attrStr = try NSMutableAttributedString(data: html.data(using:
String.Encoding.unicode, allowLossyConversion: false)!,
options: [.documentType: NSAttributedString.DocumentType.html,
.characterEncoding: String.Encoding.utf8.rawValue],
documentAttributes: nil)
// here is Your Attributed String
txtWv1.attributedText = attrStr
// Change Font or Color as per your requirement
attrStr.setFontFace(font: UIFont(name: "Roboto-Bold", size: 20)!,color: UIColor.red)
txtWv2.attributedText = attrStr
} catch let error {
print(error.localizedDescription)
}
}
}
您需要按以下步骤创建NSMutableAttributedString
的扩展名
extension NSMutableAttributedString {
func setFontFace(font: UIFont, color: UIColor? = nil) {
beginEditing()
self.enumerateAttribute(.font, in: NSRange(location: 0, length: self.length)) { (value, range, stop) in
if let f = value as? UIFont, let newFontDescriptor = f.fontDescriptor.withFamily(font.familyName).withSymbolicTraits(f.fontDescriptor.symbolicTraits) {
let newFont = UIFont(descriptor: newFontDescriptor, size: font.pointSize)
removeAttribute(.font, range: range)
addAttribute(.font, value: newFont, range: range)
if let color = color {
removeAttribute(.foregroundColor, range: range)
addAttribute(.foregroundColor, value: color, range: range)
}
}
}
endEditing()
}
}