String 如何在Swift字符串中为特定单词加下划线并更改其颜色?
我的数据源中有以下字符串 在过去的两周里,您多久会被以下问题困扰一次 当字符串显示在应用程序上时,我希望“last 2 weeks”带有下划线,并且颜色与字符串的其余部分不同String 如何在Swift字符串中为特定单词加下划线并更改其颜色?,string,swift,formatting,String,Swift,Formatting,我的数据源中有以下字符串 在过去的两周里,您多久会被以下问题困扰一次 当字符串显示在应用程序上时,我希望“last 2 weeks”带有下划线,并且颜色与字符串的其余部分不同 非常感谢您的帮助。您可以使用NSAttributedString为标签文本加下划线,并使用textColor属性更改其颜色,如下所示: let underlineAttribute = [NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleSingle.rawValue
非常感谢您的帮助。您可以使用
NSAttributedString
为标签文本加下划线,并使用textColor
属性更改其颜色,如下所示:
let underlineAttribute = [NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleSingle.rawValue]
let underlineAttributedString = NSAttributedString(string: "StringWithUnderLine", attributes: underlineAttribute)
myLabel.attributedText = underlineAttributedString
myLabel.textColor = [UIColor whiteColor];
Swift 5和4.2: 您可以从标签中调用此函数,以便在文本中的某些单词下划线并更改其颜色:
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
}
}
您也可以使用这个公认的答案,它使用IB来解决您的问题: