在 Swift 中使用 NSMutableAttributedString 更改特定文本的颜色

我遇到的问题是,我希望能够在 TextView 中更改某些文本的 textColor。我正在使用一个连接的字符串,并且只需要将字符串添加到 TextView 的文本中。似乎我想使用的是 NSMutableAttributedString,但我没有找到任何资源如何在 Swift 中使用这一点。到目前为止,我得到的是这样的东西:

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

从这里我知道我需要找到需要修改 textColor 的单词范围,然后将它们添加到属性化字符串。我需要知道的是如何从 AttributedString 中找到正确的字符串,然后更改它们的 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

因为我想要更改多个 String 的 textColor,所以我将创建一个 helper 函数来处理这个问题,但是这个函数可以用来更改 textColor。

179923 次浏览

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

要更改文本长度的颜色,您需要知道字符串中待着色字符的开始和结束索引,例如。

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


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

然后转换为属性化字符串,并在 NSForeoundColorAttributeName 中使用“ add Attribute”:

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

苹果的文档中可以找到您可以设置的其他标准属性的列表

Swift 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.helpTextUILabel的插座。

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

SWIFT 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

SWIFT 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

Chris 的回答对我有很大的帮助,所以我使用了他的方法,把它变成了一个我可以重用的函数。这让我给子字符串分配一种颜色,同时给字符串的其余部分另一种颜色。

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
}

Swift 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

答案已经给出在以前的职位,但我有一个不同的方式这样做

斯威夫特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

希望这对大家有帮助!

如果您使用的是 Swift 3x 和 UITextView,那么 NSForeground ColorAttributeName 可能无法工作(无论我尝试了什么方法,它都无法工作)。

经过一番调查,我找到了解决办法。

//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

使用不同样式(如颜色、字体等)的标签最简单的方法是在属性检查器中使用“属性”属性。只要选择文本的一部分,并改变它,你想要的

enter image description here

基于我创建字符串扩展之前的答案

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)

Swift 4.1

NSAttributedStringKey.foregroundColor

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

self.navigationController?.navigationBar.titleTextAttributes = [ NSAttributedStringKey.font: UIFont.systemFont(ofSize: 22), NSAttributedStringKey.foregroundColor: UIColor.white]

Swift 4.1

我已经改变了 在 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)

Swift 4.1

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

没问题

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

然后需要在属性化字段中选择文本,然后选择对齐方式右侧的颜色按钮。这会改变颜色。

非常简单的方法。

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

对于每一个正在寻找“ 对文本中的多个单词应用特定颜色”,我们可以做它使用 NSregarExpression

 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

您可以使用这个分机 我测试过了

Swift 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)
}


}

Swift 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

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

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
}

这可能是你的工作

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

Swift 4.2 Swift 5使字符串的各个部分着色。

在扩展 String 时使用 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

Example of using text colouring with swift 4

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

textView.linkTextAttributes = [
NSAttributedString.Key.foregroundColor: UIColor.red,
NSAttributedString.Key.underlineColor: UIColor.red,
NSAttributedString.Key.underlineStyle: NSUnderlineStyle.single.rawValue
]

请检查 cocoapod Prestyler:

Prestyler.defineRule("$", UIColor.orange)
label.attributedText = "This $text$ is orange".prestyled()

使用这个简单的函数,您可以分配文本和突出显示选定的单词。

你也可以把 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
}
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.text! . markAsMandatoryField ()

可以作为简单的扩展使用

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)


  

当使用已设置的默认颜色配置标签的文本时,此扩展可以很好地工作。

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