0

I have following string in my data source.

Over the last 2 weeks, how often have you been bothered by any of the following problems?

When the string gets displayed on the app, I would like to have "last 2 weeks" underlined and different color than rest of the string.

Any help would be greatly appreciated, thanks.

Nilesh M.
  • 165
  • 1
  • 11

2 Answers2

1

Swift 5 & 4.2:

You may call this function from your label in order to underline some of the words in a text and change their color:

extension UILabel {
    func underlineWords(words: [String]) {
        guard let textString = text else {
            return
        }
        let attributedText = NSMutableAttributedString(string: text ?? "")
        for word in words {
            let rangeToUnderline = (textString as NSString).range(of: word)
            attributedText.addAttribute(NSAttributedString.Key.underlineStyle,
                                        value: NSUnderlineStyle.single.rawValue,
                                        range: rangeToUnderline)
            attributedText.addAttribute(NSAttributedString.Key.foregroundColor,
                                        value: UIColor.red,
                                        range: rangeToUnderline)
        }
        isUserInteractionEnabled = true
        self.attributedText = attributedText
    }
}

You can also use this accepted answer which uses IB to solve your problem: Adding underline attribute to partial text UILabel in storyboard

Nilay Dagdemir
  • 236
  • 2
  • 15
0

You can underline a label's text using NSAttributedString and change its color using the textColor attribute as follows:

let underlineAttribute = [NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleSingle.rawValue]
let underlineAttributedString = NSAttributedString(string: "StringWithUnderLine", attributes: underlineAttribute)
myLabel.attributedText = underlineAttributedString
myLabel.textColor = [UIColor whiteColor];
Kyle Redfearn
  • 2,172
  • 16
  • 34