Har*_*edi 3 nsattributedstring nslocalizedstring ios swift
我有一个字符串,假设“我的名字是 %@,我在 %@ 班学习”,现在我想将要插入的占位符文本加粗,这样结果将如下所示:“我的名字很严厉,并且我在10班学习”,我会将其显示在标签上
我已经尝试过使用 NSAttributedString 但由于字符串将被本地化,我无法使用属性字符串的范围参数将其设置为粗体。
let withFormat = "my name is %@ and i study in class %@"
Run Code Online (Sandbox Code Playgroud)
有不同的方法可以做到这一点,但在我看来,最简单的方法之一是使用标签:
在占位符周围使用标签(如果需要,还可以在其他部分):
let withFormat = "my name is <b>%@</b> and i study in class <b>%@</b>"
let withFormat = "my name is [b]%@[/b] and i study in class [b]%@[/b]"
let withFormat = "my name is **%@** and i study in class **%@**"
Run Code Online (Sandbox Code Playgroud)
标签可以是 HTML、Markdown、BBCode 或您想要的任何自定义标签,然后替换占位符值:
let localized = String(format: withFormat, value1, value2)
Run Code Online (Sandbox Code Playgroud)
现在,根据您想要的方式或您使用的标签,您可以使用NSAttributedStringHTML、Markdown 等的 init,或者简单地使用NSAttributedString(string: localized),自行查找标签并应用所需的渲染效果。
这是一个小例子:
let tv = UITextView(frame: CGRect(x: 0, y: 0, width: 300, height: 130))
tv.backgroundColor = .orange
let attributedString = NSMutableAttributedString()
let htmled = String(format: "my name is <b>%@</b> and i study in class <b>%@</b>", arguments: ["Alice", "Wonderlands"])
let markdowned = String(format: "my name is **%@** and i study in class **%@**", arguments: ["Alice", "Wonderlands"])
let bbcoded = String(format: "my name is [b]%@[/b] and i study in class [b]%@[/b]", arguments: ["Alice", "Wonderlands"])
let separator = NSAttributedString(string: "\n\n")
let html = try! NSAttributedString(data: Data(htmled.utf8), options: [.documentType : NSAttributedString.DocumentType.html], documentAttributes: nil)
attributedString.append(html)
attributedString.append(separator)
let markdown = try! NSAttributedString(markdown: markdowned, baseURL: nil) //iO15+
attributedString.append(markdown)
attributedString.append(separator)
let bbcode = NSMutableAttributedString(string: bbcoded)
let regex = try! NSRegularExpression(pattern: "\\[b\\](.*?)\\[\\/b\\]", options: [])
let matches = regex.matches(in: bbcode.string, options: [], range: NSRange(location: 0, length: bbcode.length))
let boldEffect: [NSAttributedString.Key: Any] = [.font: UIFont.boldSystemFont(ofSize: 12)]
//We use reversed() because if you replace the first one, you'll remove [b] and [/b], meaning that the other ranges will be affected, so the trick is to start from the end
matches.reversed().forEach { aMatch in
let valueRange = aMatch.range(at: 1) //We use the regex group
let replacement = NSAttributedString(string: bbcode.attributedSubstring(from: valueRange).string, attributes: boldEffect)
bbcode.replaceCharacters(in: aMatch.range, with: replacement)
}
attributedString.append(bbcode)
tv.attributedText = attributedString
Run Code Online (Sandbox Code Playgroud)
输出:
| 归档时间: |
|
| 查看次数: |
4574 次 |
| 最近记录: |