I try to underline part of a string, for example, a \'string\' part in \'test string\' string. I\'m using NSMutableAttributedString
and my sol
It's September 2018, so this answer is not about iOS8 but it still relates to underlining part of a string.
Here is a Swift 4 extension that underlines a given term within an already composed myAttributedString
extension NSMutableAttributedString {
func underline(term: String) {
guard let underlineRange = string.range(of: term) else {
return
}
let startPosition = string.distance(from: term.startIndex, to: underlineRange.lowerBound)
let nsrange = NSRange(location: startPosition, length: term.count)
addAttribute(
.underlineStyle,
value: NSUnderlineStyle.styleSingle.rawValue,
range: nsrange)
}
}
Usage: myAttributedString.underline(term: "some term")