2017-08-21 9 views
3

J'utilise ce code pour ajouter des chaînes attribuées à une étiquette:changement UILabel attribué chaîne

let attrString = NSMutableAttributedString(string: text) 
// add some attributes 
myLabel.attributedText = attrString 

est-il maintenant possible de changer seul le texte de la chaîne attribué MyLabel et de garder les attributs?

+0

Oui, c'est possible. Mais vous devez faire par chaîne attribuée. –

+0

Pour autant que je sache. Nan. A chaque fois, le jeu d'étiquettes attribuait aussi du texte au dictionnaire attribué. Si vous voulez faire de cet attribut précédent une fonction ou une variable de globe. – user3589771

Répondre

1

Grâce à son mutableString propriété

Exemple:

let astrMessage = NSMutableAttributedString(string: "Hello World") 

//set some attributes 
astrMessage.addAttribute(NSAttributedStringKey.foregroundColor, 
         value: UIColor.blue, 
         range: NSRange(location: 0, length: 5)) 
astrMessage.addAttribute(NSAttributedStringKey.foregroundColor, 
         value: UIColor.red, 
         range: NSRange(location: 6, length: 5)) 

//update 
astrMessage.mutableString.setString("World Welcome") 

NOTE: Seul le premier attribut sera appliqué au texte mis à jour.

0

obtenir votre attribut label

let linkAttributes = NSMutableAttributedString(attributedString: label.attributedText) 

vous pouvez donner ajouter attribut.

linkAttributes.addAttribute(NSLinkAttributeName, value: "username://marcelofabri_", range: linkRange) 
let linkAttributes: [String : Any] = [ 
    NSForegroundColorAttributeName: UIColor.green, 
    NSUnderlineColorAttributeName: UIColor.lightGray, 
    NSUnderlineStyleAttributeName: NSUnderlineStyle.styleSingle.rawValue] 

Ajouter texte Attribuée à votre étiquette

myLabel.attributedText = linkAttributes 
+0

Et comment cela répond-il à la question du PO? Vous n'avez pas montré comment changer la propriété de chaîne de la chaîne attribuée sans changer les attributs ... –

+0

vous pouvez obtenir l'attribut label et changer un attribut –

+0

'let newAttributedString = NSMutableAttributedString (attributeString: label.attributedText)' utiliser newAttributedString pour éditer n'importe quel attribut –

0

Modifier la chaîne mutable de votre chaîne attribuée et réassigner le NSMutableAttributedString à votre étiquette.

attrString.mutableString.setString("newText") 
myLabel.attributedText = attrString 

P.S Si vous n'avez pas l'accès à votre variable de chaîne attribué, obtenir de l'étiquette.

let myAttrString = myLabel.attributedText as? NSMutableAttributedString 
if let attrString = myAttrString { 
    attrString.mutableString.setString("newText") 
    myLabel.attributedText = attrString 
}