首页 > 解决方案 > 如何在特殊字符后快速加粗文本

问题描述

我必须在字符串中的每个特殊字符之后以粗体格式制作子字符串。

例如:

@atall我正在使用stackoverflow

我怎样才能在 Swift 4 中做到这一点?

标签: iosswiftxcode

解决方案


你可以使用这样的东西:

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: "@")
}

推荐阅读