extension UILabel {
func underlineMyText(range1:String, range2:String) {
if let textString = self.text {
let str = NSString(string: textString)
let firstRange = str.range(of: range1)
let secRange = str.range(of: range2)
let attributedString = NSMutableAttributedString(string: textString)
attributedString.addAttribute(NSAttributedString.Key.underlineStyle, value: NSUnderlineStyle.single.rawValue, range: firstRange)
attributedString.addAttribute(NSAttributedString.Key.underlineStyle, value: NSUnderlineStyle.single.rawValue, range: secRange)
attributedText = attributedString
}
}
}
这样使用。
lbl.text = "By continuing you agree to our Terms of Service and Privacy Policy."
lbl.underlineMyText(range1: "Terms of Service", range2: "Privacy Policy.")