我无法使用attributionText来管理字体和粗体 . 我的场景是一个视图控制器,带有可滚动的文本视图,可接受属性文本 .
通过使用以下函数转换简单的html字符串(ul和b)来创建属性 .
多数民众赞成 . 当我稍后将文本设置为attributionData并然后设置字体时,问题出现在我的视图控制器中 .
执行文本,然后执行字体:删除显示的粗体 . 做字体,然后是文本:停止字体工作 .
我怀疑是粗体没有在字符串中表示为"bold",而是使用font-bold .
当我设置文本,然后是字体时,它会覆盖属性中的任何字体(包括粗体) . 当我设置字体,然后是文本时,属性中的字体是最后一个,并且它是使用默认字体设置的,但是正确地切换到字体的粗体版本 .
有没有办法更改attributionString上的字体并保持粗体/斜体?不是我喜欢的地方,但可以在NSAttributedString函数的选项中设置字体吗?
func html2AttributedString(fromString: String) -> NSAttributedString {
var returnString: NSAttributedString
do {
let attributedData = fromString.dataUsingEncoding(NSUnicodeStringEncoding)
let tempAttributedString = try NSAttributedString(data: attributedData!, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil)
returnString = tempAttributedString
} catch {
let tempString = "Unknown String"
let attributedData = tempString.dataUsingEncoding(NSUnicodeStringEncoding)
let tempAttributedString = try! NSAttributedString(data: attributedData!, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil)
returnString = tempAttributedString
}
return returnString
}
在View Controller中设置文本
contentTextView.attributedText = descriptionTextAttributed
contentTextView.textColor = UIColor.blackColor()
if let font = UIFont(name: "StoneSans", size: 20.0) {
contentTextView.font = font
}
更新:谢谢他的评论 .
我可以看到改变字体的三个级别:html,转换时和转换完成时 .
Wain已经提出了在转换后在belongsText中更改它的商品,但我也是CPU限制的,并且对于用户来说这些方法会明显变慢 .
我已经尝试以编程方式为html做了但它不起作用 . 如果有人可以帮忙,也许我的插入需要修复:
//let tempString = "<style> {font-family: sans-serif;}</style>" + fromString
//let tempString = "<body style='font-family=sans-serif'>" + fromString
我目前正在尝试使用documentAttributes尝试更改转换期间使用的属性(请参阅How do you use NSAttributedString?) . 此代码未编译,因为我没有正确准备documentAttributes:
if let font = UIFont(name: "StoneSans", size: CGFloat(AppData.sharedInstance.instructionFontSize)) {
do {
let attributedData = fromString.dataUsingEncoding(NSUnicodeStringEncoding)
let myAttributes:Dictionary = [
NSParagraphStyleAttributeName : NSMutableParagraphStyle(),
NSKernAttributeName : 3, // (-1,5)
NSFontAttributeName : font,
NSForegroundColorAttributeName : UIColor.whiteColor(),
NSShadowAttributeName : nil
]
let tempAttributedString = try NSAttributedString(data: attributedData!, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: myAttributes)
returnString = tempAttributedString
} catch {
let tempString = "Unknown String"
let attributedData = tempString.dataUsingEncoding(NSUnicodeStringEncoding)
let tempAttributedString = try! NSAttributedString(data: attributedData!, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil)
returnString = tempAttributedString
}
}
如果任何人都可以修改我的代码用于更改字体的两个早期方法,将不胜感激 .
蒂姆 .
1 回答
你没错,粗体和斜体信息是字体信息的一部分 . 使用
NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType
使用默认字体(或HTML中指定的任何字体) .因此,您需要编辑字体而不是仅仅替换它们,例如: