Hello! There is a line where I interpolate (string) strings from variables. I would like to change their color to highlight, for greater clarity.

Closed due to the fact that the essence of the question is not clear to the participants of Regent , Denis , user194374, Akina , Vadim Ovchinnikov 2 Feb '17 at 15:47 .

Try to write more detailed questions. To get an answer, explain what exactly you see the problem, how to reproduce it, what you want to get as a result, etc. Give an example that clearly demonstrates the problem. If the question can be reformulated according to the rules set out in the certificate , edit it .

  • You cannot change the color of the string. You can change the text color in uilabel or uitextfield. try to reformulate the question. - Max Mikheyenko
  • There is a string of string type = "My name: (name)". It is necessary to change the color of the interpolated text, that is, name. That is, the color of the text contained in the variable name. - Igor Zexyy
  • I figured out how to do it using the bottom answer, but I have to redo the whole line, but it is long ............. - Igor Zexyy

1 answer 1

You will have to use NSMutableAttributedString .

And here are two options: either decide on the forehead and use concatenation, or familiarize yourself with the NSRange and work with the bands inside the NSAttributedString .

Here is an example of the first option:

 let prefixString = "Hello " let infixAttributedString = NSAttributedString( string: "playground", attributes: [NSForegroundColorAttributeName: UIColor.blue] ) let postfixAttributedString = NSAttributedString(string: "! It's me again!") var attributedString = NSMutableAttributedString(string: prefixString) attributedString.append(infixAttributedString) attributedString.append(postfixAttributedString) 

Result:

NSMutableAttributedString result

  • I collected a string from NSMutableAttributedString but !!! I cannot add it to the array. From this array, I read a tableView. If I add a string.mutableString as a String? I can add to the array, but attributes (color of tex elements) are not saved ((((((((((( - Igor Zexyy
  • Well, of course. String and NSMutableAttributedString are a priori different data types, and dunkcasting will clean out all attributes. The type therefore contains in the title the word Attributed , which contains not only a sequence of characters, but also attributes for them. You need to create an array from NSAttributedString, and cast all strings to this type. If the table uses values ​​from an array in a UILabel, then the assignment should be done to the attributedText property, and not just text . - remenkoff