128

我遇到的问题是我希望能够更改 TextView 中某些文本的 textColor。我正在使用连接字符串,并且只想要我附加到 TextView 文本中的字符串。看来我想使用的是NSMutableAttributedString,但我没有找到任何关于如何在 Swift 中使用它的资源。我到目前为止是这样的:

let string = "A \(stringOne) with \(stringTwo)"
var attributedString = NSMutableAttributedString(string: string)
textView.attributedText = attributedString

从这里我知道我需要找到需要更改其 textColor 的单词范围,然后将它们添加到属性字符串中。我需要知道的是如何从attributeString中找到正确的字符串,然后改变它们的textColor。

由于我的评分太低,我无法回答自己的问题,但这是我找到的答案

我通过翻译从翻译一些代码找到了自己的答案

更改 NSAttributedString 中子字符串的属性

以下是 Swift 中的实现示例:

let string = "A \(stringOne) and \(stringTwo)"
var attributedString = NSMutableAttributedString(string:string)

let stringOneRegex = NSRegularExpression(pattern: nameString, options: nil, error: nil)
let stringOneMatches = stringOneRegex.matchesInString(longString, options: nil, range: NSMakeRange(0, attributedString.length))
for stringOneMatch in stringOneMatches {
    let wordRange = stringOneMatch.rangeAtIndex(0)
    attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.nameColor(), range: wordRange)
}

textView.attributedText = attributedString

由于我想更改多个字符串的 textColor,我将创建一个辅助函数来处理此问题,但这适用于更改 textColor。

4

25 回答 25

140
let mainString = "Hello World"
let stringToColor = "World"

斯威夫特 5

let range = (mainString as NSString).range(of: stringToColor)

let mutableAttributedString = NSMutableAttributedString.init(string: mainString)
mutableAttributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.red, range: range)

textField = UITextField.init(frame: CGRect(x:10, y:20, width:100, height: 100))
textField.attributedText = mutableAttributedString

斯威夫特 4.2

let range = (mainString as NSString).range(of: stringToColor)
    

let mutableAttributedString = NSMutableAttributedString.init(string: mainString)
mutableAttributedString.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.red, range: range)     
    
textField = UITextField.init(frame: CGRect(x:10, y:20, width:100, height: 100))
textField.attributedText = mutableAttributedString
于 2016-09-22T13:11:44.563 回答
112

我看到您已经回答了一些问题,但是为了提供一种更简洁的方式而不使用正则表达式来回答标题问题:

要更改一段文本的颜色,您需要知道字符串中已着色字符的开始和结束索引,例如

var main_string = "Hello World"
var string_to_color = "World"

var range = (main_string as NSString).rangeOfString(string_to_color)

然后您转换为属性字符串并使用带有 NSForegroundColorAttributeName 的“添加属性”:

var attributedString = NSMutableAttributedString(string:main_string)
attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor() , range: range)

您可以在Apple 的文档中找到可以设置的更多标准属性列表

于 2014-08-11T16:52:43.117 回答
48

斯威夫特 2.1 更新:

 let text = "We tried to make this app as most intuitive as possible for you. If you have any questions don't hesitate to ask us. For a detailed manual just click here."
 let linkTextWithColor = "click here"

 let range = (text as NSString).rangeOfString(linkTextWithColor)

 let attributedString = NSMutableAttributedString(string:text)
 attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor() , range: range)

 self.helpText.attributedText = attributedString

self.helpText是一个UILabel出口。

于 2016-01-03T12:45:29.853 回答
33

Swift 4.2Swift 5对字符串的部分进行着色。

在扩展字符串时使用 NSMutableAttributedString 的一种非常简单的方法。这也可用于为整个字符串中的多个单词着色。

import UIKit

extension String {
    func attributedStringWithColor(_ strings: [String], color: UIColor, characterSpacing: UInt? = nil) -> NSAttributedString {
        let attributedString = NSMutableAttributedString(string: self)
        for string in strings {
            let range = (self as NSString).range(of: string)
            attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: color, range: range)
        }

        guard let characterSpacing = characterSpacing else {return attributedString}

        attributedString.addAttribute(NSAttributedString.Key.kern, value: characterSpacing, range: NSRange(location: 0, length: attributedString.length))

        return attributedString
    }
}

现在您可以在任何您想要的视图控制器上全局使用:

let attributedWithTextColor: NSAttributedString = "Doc, welcome back :)".attributedStringWithColor(["Doc", "back"], color: UIColor.black)

myLabel.attributedText = attributedWithTextColor

使用 swift 4 的文本着色示例

于 2019-01-29T08:29:04.520 回答
11

以前的帖子中已经给出了答案,但我有不同的方法

斯威夫特 3 倍:

var myMutableString = NSMutableAttributedString()

myMutableString = NSMutableAttributedString(string: "Your full label textString")

myMutableString.setAttributes([NSFontAttributeName : UIFont(name: "HelveticaNeue-Light", size: CGFloat(17.0))!
        , NSForegroundColorAttributeName : UIColor(red: 232 / 255.0, green: 117 / 255.0, blue: 40 / 255.0, alpha: 1.0)], range: NSRange(location:12,length:8)) // What ever range you want to give

yourLabel.attributedText = myMutableString

希望这对任何人都有帮助!

于 2017-01-11T10:49:01.683 回答
10

Chris 的回答对我帮助很大,所以我用了他的方法,变成了一个我可以重复使用的 func。这让我为子字符串指定颜色,同时为字符串的其余部分指定另一种颜色。

static func createAttributedString(fullString: String, fullStringColor: UIColor, subString: String, subStringColor: UIColor) -> NSMutableAttributedString
{
    let range = (fullString as NSString).rangeOfString(subString)
    let attributedString = NSMutableAttributedString(string:fullString)
    attributedString.addAttribute(NSForegroundColorAttributeName, value: fullStringColor, range: NSRange(location: 0, length: fullString.characters.count))
    attributedString.addAttribute(NSForegroundColorAttributeName, value: subStringColor, range: range)
    return attributedString
}
于 2016-09-22T15:10:12.253 回答
8

斯威夫特 4.1

NSAttributedStringKey.foregroundColor

例如,如果您想更改 NavBar 中的字体:

self.navigationController?.navigationBar.titleTextAttributes = [ NSAttributedStringKey.font: UIFont.systemFont(ofSize: 22), NSAttributedStringKey.foregroundColor: UIColor.white]
于 2018-05-10T14:27:08.240 回答
6

你可以使用我测试过的这个扩展

迅捷4.2

import Foundation
import UIKit

extension NSMutableAttributedString {

    convenience init (fullString: String, fullStringColor: UIColor, subString: String, subStringColor: UIColor) {
           let rangeOfSubString = (fullString as NSString).range(of: subString)
           let rangeOfFullString = NSRange(location: 0, length: fullString.count)//fullString.range(of: fullString)
           let attributedString = NSMutableAttributedString(string:fullString)
           attributedString.addAttribute(NSAttributedStringKey.foregroundColor, value: fullStringColor, range: rangeOfFullString)
           attributedString.addAttribute(NSAttributedStringKey.foregroundColor, value: subStringColor, range: rangeOfSubString)

           self.init(attributedString: attributedString)
   }

}
于 2018-09-17T06:37:07.070 回答
4

斯威夫特 2.2

var myMutableString = NSMutableAttributedString()

myMutableString = NSMutableAttributedString(string: "1234567890", attributes: [NSFontAttributeName:UIFont(name: kDefaultFontName, size: 14.0)!])

myMutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor(red: 0.0/255.0, green: 125.0/255.0, blue: 179.0/255.0, alpha: 1.0), range: NSRange(location:0,length:5))

self.lblPhone.attributedText = myMutableString
于 2016-10-13T09:01:24.620 回答
4

根据我创建字符串扩展之前的答案

extension String {

func highlightWordsIn(highlightedWords: String, attributes: [[NSAttributedStringKey: Any]]) -> NSMutableAttributedString {
     let range = (self as NSString).range(of: highlightedWords)
     let result = NSMutableAttributedString(string: self)

     for attribute in attributes {
         result.addAttributes(attribute, range: range)
     }

     return result
    }
}

您可以将文本的属性传递给方法

像这样打电话

  let attributes = [[NSAttributedStringKey.foregroundColor:UIColor.red], [NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: 17)]]
  myLabel.attributedText = "This is a text".highlightWordsIn(highlightedWords: "is a text", attributes: attributes)
于 2018-04-26T10:39:36.710 回答
4

斯威夫特 4.1

我已经改变了这个 In Swift 3

let str = "Welcome "
let welcomeAttribute = [ NSForegroundColorAttributeName: UIColor.blue()]
let welcomeAttrString = NSMutableAttributedString(string: str, attributes: welcomeAttribute)

这在 Swift 4.0 中

let str = "Welcome "
let welcomeAttribute = [ NSAttributedStringKey.foregroundColor: UIColor.blue()]
let welcomeAttrString = NSMutableAttributedString(string: str, attributes: welcomeAttribute)

斯威夫特 4.1

let str = "Welcome "
let welcomeAttribute = [ NSAttributedStringKey(rawValue: NSForegroundColorAttributeName): UIColor.blue()]
let welcomeAttrString = NSMutableAttributedString(string: str, attributes: welcomeAttribute)

工作正常

于 2018-05-24T08:05:13.417 回答
4

使用不同样式(如颜色、字体等)进行标签的最简单方法是在 Attributes Inspector 中使用属性“Attributed”。只需选择部分文本并根据需要进行更改

在此处输入图像描述

于 2017-10-07T12:14:06.817 回答
3

迅捷4.2

    let textString = "Hello world"
    let range = (textString as NSString).range(of: "world")
    let attributedString = NSMutableAttributedString(string: textString)

    attributedString.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.red, range: range)
    self.textUIlable.attributedText = attributedString
于 2018-11-06T09:11:18.503 回答
3

使用这个简单的功能,您可以分配文本并突出显示所选单词。

您还可以将UITextView更改为UILabel等。

func highlightBoldWordAtLabel(textViewTotransform: UITextView, completeText: String, wordToBold: String){
    textViewToTransform.text = completeText
    let range = (completeText as NSString).range(of: wordToBold)
    let attribute = NSMutableAttributedString.init(string: completeText)

    attribute.addAttribute(NSAttributedString.Key.font, value: UIFont.boldSystemFont(ofSize: 16), range: range)
    attribute.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.black , range: range)
    textViewToTransform.attributedText = attribute
}
于 2020-01-29T17:26:38.913 回答
3

这可能对你有用

let main_string = " User not found,Want to review ? Click here"
    let string_to_color = "Click here"

    let range = (main_string as NSString).range(of: string_to_color)

    let attribute = NSMutableAttributedString.init(string: main_string)
    attribute.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.blue , range: range)

    lblClickHere.attributedText = attribute
于 2019-01-01T07:55:05.653 回答
2

您可以使用简单的扩展

extension String{

func attributedString(subStr: String) -> NSMutableAttributedString{
    let range = (self as NSString).range(of: subStr)
    let attributedString = NSMutableAttributedString(string:self)
    attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.red , range: range)
    
    return attributedString
  }
}

myLable.attributedText = fullStr.attributedString(subStr: strToChange)

  
于 2020-08-05T10:12:01.497 回答
2

对于所有正在寻找“将特定颜色应用于文本中的多个单词”的人,我们可以使用NSRegularExpression

 func highlight(matchingText: String, in text: String) {
    let attributedString  = NSMutableAttributedString(string: text)
    if let regularExpression = try? NSRegularExpression(pattern: "\(matchingText)", options: .caseInsensitive) {
        let matchedResults = regularExpression.matches(in: text, options: [], range: NSRange(location: 0, length: attributedString.length))
        for matched in matchedResults {
             attributedString.addAttributes([NSAttributedStringKey.backgroundColor : UIColor.yellow], range: matched.range)

        }
        yourLabel.attributedText = attributedString
    }
}

参考链接:https ://gist.github.com/aquajach/4d9398b95a748fd37e88

于 2018-09-06T12:23:20.690 回答
2

此扩展在使用已设置的默认颜色配置标签文本时效果很好。

public extension String {
    func setColor(_ color: UIColor, ofSubstring substring: String) -> NSMutableAttributedString {
        let range = (self as NSString).range(of: substring)
        let attributedString = NSMutableAttributedString(string: self)
        attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: color, range: range)
        return attributedString
    }
}

例如

let text = "Hello World!"
let attributedText = text.setColor(.blue, ofSubstring: "World")

let myLabel = UILabel()
myLabel.textColor = .white
myLabel.attributedText = attributedText
于 2021-01-30T09:29:02.250 回答
1

超级简单的方法来做到这一点。

let text = "This is a colorful attributed string"
let attributedText = 
NSMutableAttributedString.getAttributedString(fromString: text)
attributedText.apply(color: .red, subString: "This")
//Apply yellow color on range
attributedText.apply(color: .yellow, onRange: NSMakeRange(5, 4))

有关更多详细信息,请单击此处: https ://github.com/iOSTechHub/AttributedString

于 2018-09-02T17:54:58.363 回答
1

您可以使用此方法。我在我的通用实用程序类中实现了这个方法来全局访问。

func attributedString(with highlightString: String, normalString: String, highlightColor: UIColor) -> NSMutableAttributedString {
    let attributes = [NSAttributedString.Key.foregroundColor: highlightColor]
    let attributedString = NSMutableAttributedString(string: highlightString, attributes: attributes)
    attributedString.append(NSAttributedString(string: normalString))
    return attributedString
}
于 2018-11-16T11:09:24.573 回答
1

要更改字体颜色的颜色,首先选择属性而不是如下图所示的普通

然后,您需要选择属性字段中的文本,然后选择对齐右侧的颜色按钮。这将改变颜色。

于 2018-08-30T00:33:22.733 回答
0

如果您使用的是 Swift 3x 和 UITextView,则 NSForegroundColorAttributeName 可能不起作用(无论我尝试什么方法,它都对我不起作用)。

所以,经过一番挖掘,我找到了解决方案。

//Get the textView somehow
let textView = UITextView()
//Set the attributed string with links to it
textView.attributedString = attributedString
//Set the tint color. It will apply to the link only
textView.tintColor = UIColor.red
于 2017-05-18T19:30:10.833 回答
0

请检查 cocoapod Prestyler

Prestyler.defineRule("$", UIColor.orange)
label.attributedText = "This $text$ is orange".prestyled()
于 2019-03-04T18:50:03.440 回答
0

您需要更改 textview 参数,而不是属性字符串的参数

textView.linkTextAttributes = [
        NSAttributedString.Key.foregroundColor: UIColor.red,
        NSAttributedString.Key.underlineColor: UIColor.red,
        NSAttributedString.Key.underlineStyle: NSUnderlineStyle.single.rawValue
    ]
于 2019-02-06T13:53:13.450 回答
0
extension String{
// to make text field mandatory * looks
mutating func markAsMandatoryField()-> NSAttributedString{

    let main_string = self
    let string_to_color = "*"
    let range = (main_string as NSString).range(of: string_to_color)
    print("The rang = \(range)")
    let attribute = NSMutableAttributedString.init(string: main_string)
    attribute.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.rgbColor(red: 255.0, green: 0.0, blue: 23.0) , range: range)
     return attribute
}

}

使用 EmailLbl.attributedText = EmailLbl.text!.markAsMandatoryField()

于 2020-05-11T16:39:39.927 回答