let withFormat = "my name is %@ and i study in class %@"
有不同的方法可以做到这一点,但在我看来,最简单的方法之一是使用标签:
在占位符周围使用标签(如果需要,还可以使用其他部分):
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 **%@**"
标签可以是 HTML、Markdown、BBCode 或任何您喜欢的自定义,然后替换占位符值:
let localized = String(format: withFormat, value1, value2)
现在,根据你想怎么做,或者你使用哪个标签,你可以使用来自 HTML、Markdown 等的 NSAttributedString 的 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
输出: