2017-10-11 5 views
2

Comment une chaîne au format NSAttributedString peut-elle être ajoutée à une chaîne au format textView.attributedText existante à partir de UITextView?Ajoute une chaîne formatée à une chaîne déjà formatée provenant de UITextView?

De this answer, je peux voir que la conversion de et vers NSMutableAttributedString/NSAttributedString peut être fait avec appendAttributedString()/append() mais ce ne fonctionne pas quand je tire et mettre à jour un textView.attributedText comme ceci:

let string2 = NSAttributedString(string: "success", attributes: [NSAttributedStringKey.foregroundColor: UIColor.green]) 

let newMutableString = textView.attributedText.copy() as! NSMutableAttributedString 
newMutableString.append(string2) 

textView.attributedText = newMutableString.copy() as! NSAttributedString 

Message d'erreur:

Could not cast value of type 'NSConcreteAttributedString' (0x10c7dff30) to 'NSMutableAttributedString' (0x10c7dff80). 
+0

Pourquoi appelez-vous '.copy()' sur vos chaînes? – LinusGeffarth

+0

@LinusGeffarth J'ai essayé de me moquer de cette autre réponse ... Pas de vraie raison. Je vais essayer de l'enlever. – powtac

+1

@LinusGeffarth semble que la réponse de @ tnguyen est la solution! :-) – powtac

Répondre

3

Je crois que vous devez copier avec mutableCopy becaus e vous voulez obtenir une copie mutable à partir d'un fichier non modifiable:

let newMutableString = textView.attributedText.mutableCopy() as! NSMutableAttributedString 
+0

Wow c'est tout! Merci beaucoup! – powtac