Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
String 如何在Swift字符串中为特定单词加下划线并更改其颜色?_String_Swift_Formatting - Fatal编程技术网

String 如何在Swift字符串中为特定单词加下划线并更改其颜色?

String 如何在Swift字符串中为特定单词加下划线并更改其颜色?,string,swift,formatting,String,Swift,Formatting,我的数据源中有以下字符串 在过去的两周里,您多久会被以下问题困扰一次 当字符串显示在应用程序上时,我希望“last 2 weeks”带有下划线,并且颜色与字符串的其余部分不同 非常感谢您的帮助。您可以使用NSAttributedString为标签文本加下划线,并使用textColor属性更改其颜色,如下所示: let underlineAttribute = [NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleSingle.rawValue

我的数据源中有以下字符串

在过去的两周里,您多久会被以下问题困扰一次

当字符串显示在应用程序上时,我希望“last 2 weeks”带有下划线,并且颜色与字符串的其余部分不同


非常感谢您的帮助。

您可以使用
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来解决您的问题: