例如,我正在编写一个函数,我想显示一个add方法。我想在上面的评论下面这样强调。
// 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
}
您只需制作一个扩展即可:
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
}
}
如何使用它?
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
}}