-5

I have to make substrings in bold format after each special character in a string.

For Example:

Hi @atall I'm using stackoverflow

How can I do that in Swift 4?

nitin.agam
  • 1,949
  • 1
  • 17
  • 24
TillMoss
  • 37
  • 6
  • 1
    You can check [this](https://stackoverflow.com/questions/28496093/making-text-bold-using-attributed-string-in-swift) and [this](https://stackoverflow.com/questions/36486761/make-part-of-a-uilabel-bold-in-swift/36486949) to see how text is made **bold**. Once you make an effort, please [edit](https://stackoverflow.com/posts/58166971/edit) your question and add the code you tried. – Kamran Sep 30 '19 at 11:32

2 Answers2

2

You can use use something like this:

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
    }
}

And then for your special case, you could a convenience method:

extension String {
    // ...

    var mentionsHighlighted: NSAttributedString = self.wordsHighlighted(after: "@")
}
henrik-dmg
  • 1,448
  • 16
  • 23
1

An alternative solution is underestimated 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)
    }
}
vadian
  • 274,689
  • 30
  • 353
  • 361