【问题标题】:How to bold text in swift after special character如何在特殊字符后快速加粗文本
【发布时间】:2019-09-30 11:26:06
【问题描述】:

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

例如:

@atall我正在使用stackoverflow

如何在 Swift 4 中做到这一点?

【问题讨论】:

  • 您可以查看thisthis 了解文本是如何加粗的。一旦你做出努力,请edit你的问题并添加你尝试过的代码。

标签: ios swift xcode


【解决方案1】:

你可以使用这样的东西:

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

【讨论】:

  • 更简单的模式:"\\S+"(一个或多个非空白字符)
【解决方案2】:

另一种解决方案被低估了enumerateSubstrings(in:options:_:)

let string = "Hi @atall I'm using stackoverflow"
let size = UIFont.systemFontSize

var attributedString = NSMutableAttributedString(string: string)
string.enumerateSubstrings(in: string.startIndex..., options: .byWords) { (substring, substringRange, _, _) in
    if substring != nil, substringRange.lowerBound != string.startIndex, string[string.index(before: substringRange.lowerBound)] == "@" {
        let range = NSRange(substringRange, in: string) // range without @
        let adjustedRange = NSRange(location: range.location - 1, length: range.length + 1)  // range with @
        attributedString.addAttribute(.font, value: UIFont.boldSystemFont(ofSize: size), range: adjustedRange)
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-12
    • 2014-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多