Changer la couleur d'un texte spécifique en utilisant Nsmutatattributedstring dans Swift
la question que j'ai est que je veux être en mesure de changer la couleur de texte de certains textes dans un TextView. J'utilise une chaîne concaténée, et je veux juste les chaînes que j'ajoute dans le texte de TextView. Il semble que ce que je veux utiliser est NSMutableAttributedString
, mais je ne trouve pas de ressources sur la façon de L'utiliser dans Swift. Ce que j'ai jusqu'à présent est quelque chose comme ceci:
let string = "A (stringOne) with (stringTwo)"
var attributedString = NSMutableAttributedString(string: string)
textView.attributedText = attributedString
D'ici je sais que j'ai besoin de trouver la gamme de mots qui ont besoin d'avoir leur textColor a changé et puis les ajoute à la chaîne attribuée. Ce que j'ai besoin de savoir c'est comment trouver les chaînes correctes à partir de l'attributedString, et ensuite changer leur textColor.
depuis que j'ai trop bas d'une cote, Je ne peux pas répondre à ma propre question, Mais voici la réponse que j'ai trouvé
j'ai trouvé ma propre réponse en traduisant à partir de la traduction d'un certain code de
Changer les attributs des sous-chaînes dans un NSAttributedString
Voici l'exemple de mise en œuvre dans 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
puisque je veux changer la couleur du texte de plusieurs chaînes, je vais faire une fonction d'aide pour gérer cela, mais cela fonctionne pour changer la couleur du texte.
15 réponses
je vois que vous avez répondu à la question un peu, mais pour fournir une manière un peu plus concise sans utiliser regex pour répondre à la question du titre:
pour changer la couleur d'une longueur de texte, vous devez connaître l'index de début et de fin des caractères colorés dans la chaîne par exemple
var main_string = "Hello World"
var string_to_color = "World"
var range = (main_string as NSString).rangeOfString(string_to_color)
puis vous convertissez en chaîne attribuée et utilisez 'add attribut' avec NSForegroundColorAttributeName:
var attributedString = NSMutableAttributedString(string:main_string)
attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor() , range: range)
une liste d'autres attributs standards que vous pouvez définir peut être trouvée dans la documentation D'Apple
SWIFT 4.0
let txtfield1 :UITextField!
let main_string = "Hello World"
let string_to_color = "World"
let range = (main_string as NSString).range(of: string_to_color)
let attribute = NSMutableAttributedString.init(string: main_string)
attribute.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.red , range: range)
txtfield1 = UITextField.init(frame:CGRect(x:10 , y:20 ,width:100 , height:100))
txtfield1.attributedText = attribute
Swift 2.1 Mise À Jour:
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
est une sortie UILabel
.
la réponse est déjà donnée dans les billets précédents mais j'ai une façon différente de le faire
Swift 3x:
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
Espérons que cela aide quelqu'un!
la réponse de Chris m'a été d'une grande aide, donc j'ai utilisé son approche et je me suis transformé en func que je peux réutiliser. Ceci me permet d'assigner une couleur à un substrat tout en donnant au reste de la chaîne une autre couleur.
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 4.1
NSAttributedStringKey.foregroundColor
par exemple si vous voulez changer la police dans NavBar:
self.navigationController?.navigationBar.titleTextAttributes = [ NSAttributedStringKey.font: UIFont.systemFont(ofSize: 22), NSAttributedStringKey.foregroundColor: UIColor.white]
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
basé sur les réponses avant que j'ai créé une extension de chaîne de caractères
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
}
}
vous pouvez passer les attributs pour le texte à la méthode
appelez comme ça
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)
la façon la plus facile de faire étiquette avec un style différent tel que la couleur, la police, etc. utilisez la propriété "attribuée" dans attributs Inspecteur. Il suffit de choisir une partie du texte et de le modifier comme vous le souhaitez
Swift 4.1
j'ai changé de ceci En Swift 3
let str = "Welcome "
let welcomeAttribute = [ NSForegroundColorAttributeName: UIColor.blue()]
let welcomeAttrString = NSMutableAttributedString(string: str, attributes: welcomeAttribute)
et ceci dans 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)
Fonctionne très bien
si vous utilisez Swift 3x et UITextView, peut-être que le nom de fichier NSForegroundColorAttributeName ne fonctionnera pas (cela n'a pas fonctionné pour moi quelle que soit l'approche que j'ai essayé).
Donc, après quelques recherches, j'ai trouvé une solution.
//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
pour changer la couleur de la police de couleur, sélectionnez d'abord attribué au lieu de simple comme dans l'image ci-dessous
, Vous devez ensuite sélectionner le texte dans la attribué champ et sélectionnez le bouton de couleur sur le côté droit de les alignements. Cela va changer la couleur.
très facile à faire.
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))
Pour plus de détails cliquez ici: https://github.com/iOSTechHub/AttributedString
pour tous ceux qui cherchent " appliquer une couleur spécifique à plusieurs mots dans le texte ", nous pouvons le faire en utilisant 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
}
}
lien de référence: https://gist.github.com/aquajach/4d9398b95a748fd37e88
vous pouvez utiliser cette extension Je l'ai tester sur
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)
}
}