Sak*_*boy 5 accessibility nsattributedstring uifont ios ios9
我需要解析包含<b>(粗体),<i>(斜体)和<u>(下划线)标签的基本HTML字符串,没有别的,只是那些简单的标签.
现在,我只能得到<u>(下划线)标签在正确渲染NSAttributedString,使用新的时San Francisco中iOS 9.
我真的需要得到<b>(粗体)和<i>(斜体)渲染.
这是我正在做的事情:
let text = "<i>Any</i> <b>Text</b> <u>that's basic HTML</u>"
let font = UIFont.preferredFontForTextStyle(UIFontTextStyleBody)
let modifiedFont = NSString(format:"<span style=\"font-family: '-apple-system','HelveticaNeue'; font-size: %f \">%@</span>",
font.pointSize, text) as String
let data = (modifiedFont as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let attributedString = try? NSAttributedString(data: data!, options:
[ NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute : NSUTF8StringEncoding,
NSFontAttributeName : font ],
documentAttributes: nil)
Run Code Online (Sandbox Code Playgroud)
但不幸的是,<i>(斜体)和<b>(粗体)标签永远不会渲染,只有<u>(下划线)正确渲染.
这个相同的方法用于iOS 8处理Helvetica-Neue字体,但它不适用于新iOS 9 San Francisco字体
帮助我<b>(粗体)和<i>(斜体)正确渲染NSAttributedString!
更新:我也在整个应用程序中使用动态文本.这可能是事情不起作用的原因......
在应用程序中同时使用NSAttributedString和DynamicType是导致问题的原因。
事实证明,你NEED重新解析/渲染你String收到后UIContentSizeCategoryDidChangeNotification。您不能保留NSAttributedString,然后使用它来重置UILabel. 您必须重新解析/渲染NSAttributedString.
简要示例:
public override func viewDidLoad() {
super.viewDidLoad()
//register be notified when text size changes.
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("didChangePreferredContentSize:"), name: UIContentSizeCategoryDidChangeNotification, object: nil)
}
// The action Selector that gets called after the text size has been changed.
func didChangePreferredContentSize(notification: NSNotification) {
self.myLabel.font = UIFont.preferredFontForTextStyle(UIFontTextStyleSubheadline)
//
// DO NOT do this:
// self.myLabel.attributedText = self.myAlreadyRenderedText
//
//Make sure you re-render/parse the text into a new NSAttributedString.
//Do THIS instead:
self.myLabel.attributedText = self.renderAttributedText(str)
}
//Our method to render/parse the HTML tags in our text. Returns an NSAttributedString.
func renderAttributedText(str: String) -> NSAttributedString? {
let text = "<i>Any</i> <b>Text</b> <u>that's basic HTML</u>"
let font = UIFont.preferredFontForTextStyle(UIFontTextStyleBody)
let modifiedFont = NSString(format:"<span style=\"font-family: '-apple-system','HelveticaNeue'; font-size: %f \">%@</span>",font.pointSize, text) as String
let data = (modifiedFont as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let attributedString = try? NSAttributedString(data: data!, options:
[ NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute : NSUTF8StringEncoding,
NSFontAttributeName : font ],
documentAttributes: nil)
return attributedString
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2116 次 |
| 最近记录: |