cod*_*ojo 5 nsattributedstring nslocalizedstring swift
我有一个方法将NSAttributedString设置为粗体:
func setBold(text: String) -> NSMutableAttributedString {
guard let font = UIFont.CustomNormalBoldItalic() else {
fatalError("font not found")
}
let string = NSMutableAttributedString(string:"\(text)", attributes: [NSFontAttributeName : font])
self.setAttributedString(string)
return self
}
Run Code Online (Sandbox Code Playgroud)
这就是它的调用方式,它正常工作:
let formattedString = NSMutableAttributedString()
formattedString.setBold("Your text here")
Run Code Online (Sandbox Code Playgroud)
但是,我试图将NSLocalizedString的子字符串的文本设置为粗体.所以我会这样尝试:
let formattedString = NSMutableAttributedString()
return NSAttributedString(string: String.localizedStringWithFormat(
NSLocalizedString("message", comment: ""),
formattedString.setBold(NSLocalizedString("message.day", comment: "")),
NSLocalizedString("message.time", comment: "")
))
Run Code Online (Sandbox Code Playgroud)
它不是" 今天晚上10点开始",而是提供以下输出:
Today{
NSFont = "<UICTFont: 0x7fb75d4f1330> font-family: \"CustomText-MediumItalic\"; font-weight: normal; font-style: italic; font-size: 14.00pt";
} starting at 10pm {
}
Run Code Online (Sandbox Code Playgroud)
任何人都可以告诉我我哪里出错或如何解决这个问题?我有另一种方法的原因是因为我有许多LocalizedStrings来设置粗体,并认为这可能是一个简单的解决方案.对不涉及大量重复/代码行的其他想法/解决方案开放.
我只需将外部字符串制作为 html 并让其AttributedString处理繁重的工作。这是 swift 3,但 swift 2.3 应该同样简单。还需要添加一些可选处理,但您已经了解了其要点。
// samples so I don't have to put a string resource in my playground, you
// could just as easily pull these from NSLocalizedString
let format = "<b>%1$@</b> starting at <b>%2$@</b>"
let day = "Today"
let time = "10 PM"
let raw = String(format:format, day, time)
let attr = AttributedString(
html: raw.data(using: .utf8)!,
options: [NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType],
documentAttributes:nil
)!
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
536 次 |
| 最近记录: |