【发布时间】:2016-05-14 00:28:54
【问题描述】:
我无法让属性文本同时管理字体和粗体。 我的场景是一个带有可滚动文本视图的视图控制器,它接受属性文本。
属性是通过以下函数转换一个简单的 html 字符串(ul's 和 b's)来创建的。
没关系。当我稍后将文本设置为属性数据然后设置字体时,问题出现在我的视图控制器中。
先做文字,再做字体:去掉粗体显示。 做字体,然后是文本:使字体停止工作。
我怀疑粗体在字符串中没有表示为“粗体”,而是使用 font-bold。
当我设置文本,然后是字体时,它会覆盖属性中的任何字体(包括粗体)。
当我设置字体,然后是文本时,属性中的字体是最后一个,并且设置了默认字体但正确切换到字体的粗体版本。
有没有办法改变属性字符串上的字体并保持粗体/斜体? 不是我喜欢的地方,但是字体可以在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
}
在视图控制器中设置文本
contentTextView.attributedText = descriptionTextAttributed
contentTextView.textColor = UIColor.blackColor()
if let font = UIFont(name: "StoneSans", size: 20.0) {
contentTextView.font = font
}
更新:感谢 Wain 的 cmets。
我可以看到更改字体的三个级别:html、转换时和转换完成时。
Wain 提出了在属性文本转换后更改它的方法,但我也受到 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
}
}
如果有人可以修复我的代码以更改字体的两种较早的方法,将不胜感激。
提姆。
【问题讨论】:
标签: ios swift fonts nsattributedstring