ios - 如何在特殊字符后快速加粗文本
问题描述
我必须在字符串中的每个特殊字符之后以粗体格式制作子字符串。
例如:
嗨@atall我正在使用stackoverflow
我怎样才能在 Swift 4 中做到这一点?
解决方案
你可以使用这样的东西:
extension String {
func wordsHighlighted(after character: Character, fontSize: CGFloat = UIFont.systemFontSize) -> NSAttributedString {
var attributedString = NSMutableAttributedString(string: self)
do {
let regex = try NSRegularExpression(pattern: String(character) + ".+\\s")
let results = regex.matches(in: self,
range: NSRange(self.startIndex..., in: self))
results.forEach { result in
attributedString.addAttributes(
[.font: UIFont.boldSystemFont(ofSize: fontSize)],
range: result.range)
}
} catch let error {
// Handle error here
}
return attributedString
}
}
然后对于您的特殊情况,您可以使用一种方便的方法:
extension String {
// ...
var mentionsHighlighted: NSAttributedString = self.wordsHighlighted(after: "@")
}
推荐阅读
- python - 使用 pandas 删除 csv 文件中的特定行
- javascript - 根据当前 viewZoom 设置可变 XYZ 源和缩放增量
- apache-spark - --master local[n] 和 --total-executor-core = n (Spark Standalone) 有什么区别?
- java - 从主机系统和 docker 容器读取文本文件会产生不同的结果
- html - CSS 翻译忽略 z-index
- sql - 通过 hiveql 添加组 id
- redis - OpenShift - 用于导入图像的凭据查找
- unity3d - 对 Unity 组件重置做出反应
- powershell - 如何使用一个许可证而不是另一个许可证找到 o365 用户
- c# - 使用 System.Text.Json.Serialization 将动态对象转换为 json 时引发异常