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