是否可以突出显示文本中的一个单词?

时间:2018-07-19 04:04:01

标签: ios swift

我要突出显示xxx.strings文件中定义的句子的一个单词,例如突出显示“请单击允许”的句子中的“允许”。

2 个答案:

答案 0 :(得分:0)

您好,请参考以下方法:-

func underline() {
    if let textString = self.text {
        let attributedString = NSMutableAttributedString(string: textString)
        let range = (self.text! as NSString).range(of: "your highlighted string")
        attributedString.addAttributes([NSAttributedStringKey.underlineColor : .white], range: range)
        attributedText = attributedString
    }
}

希望它将对您有帮助, 谢谢。

答案 1 :(得分:0)

是的,您可以使用NSAttributed String将不同的属性应用于字符串,例如

下划线

    let attributedString = NSMutableAttributedString(string: textString)
    let range = (self.text! as NSString).range(of: "your string you want to highlight")
    attributedString.addAttributes([NSAttributedStringKey.underlineStyle: NSUnderlineStyle.styleSingle.rawValue,NSAttributedStringKey.underlineColor : .white], range: range)
    yourlabel.attributedText = attributedString

更改字符串颜色(原色)

let attributedString = NSMutableAttributedString(string: textString)
    let range = (self.text! as NSString).range(of: "your string you want to highlight")
    attributedString.addAttributes([NSAttributedStringKey.foregroundColor : UIColor.red], range: range)
    yourlabel.attributedText = attributedString

更改字符串颜色(背景色)

let attributedString = NSMutableAttributedString(string: textString)
    let range = (self.text! as NSString).range(of: "your string you want to highlight")
    attributedString.addAttributes([NSAttributedStringKey.backgroundColor : UIColor.red], range: range)
    yourlabel.attributedText = attributedString

更改字体

let attributedString = NSMutableAttributedString(string: textString)
    let range = (self.text! as NSString).range(of: "your string you want to highlight")
    attributedString.addAttributes([NSAttributedStringKey.font : fontyouwant], range: range)
    yourlabel.attributedText = attributedString