0

For example, I'm writing a function which I want to show an add method. I wanted to underline the comment above like so.

// This is the comment I want to underline 
// Adding a few other things you can do with comments would also be helpful

func helpMeUnderlineThisComment(comment: String) -> String {
     for char in comment {
        if char == comment {
          return char.underlined()
        }
     }
     return nil
}

1 Answers1

0

You can simply do it by making an extension:

extension NSAttributedString {
var underlined: NSAttributedString {
    return applying(attributes: [.underlineStyle: NSUnderlineStyle.single.rawValue])
}

func applying(attributes: [NSAttributedString.Key: Any]) -> NSAttributedString {
    let copy = NSMutableAttributedString(attributedString: self)
    let range = (string as NSString).range(of: string)
    copy.addAttributes(attributes, range: range)
    return copy
}
}

How to use it?

class ViewController: UIViewController {
@IBOutlet weak var textLabel: UILabel!
override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
    self.textLabel.text = "Some Text"
    self.textLabel.attributedText = textLabel.attributedText?.underlined
}}
Abhishek Patel
  • 121
  • 1
  • 1
  • 11