Multiple colours in an NSString
or NSMutableStrings
are not possible. So I've heard a little about the NSAttributedString
which was introduced with the iPad SDK 3.2 (or around 3.2) and is available on the iPhone as of iPhone SDK 4.0 beta.
I would like to have a string that has three colours.
The reason I don't use 3 separate NSStrings, is because the length of each of the three NSAttributedString
substrings changes often and so I would prefer, not to use any calculations to re-position 3 separate NSString
objects.
If it's possible using NSAttributedString
how do I make the following - (if not possible with NSAttributed string how would you do it):
Edit:
Remember, @"first"
, @"second"
and @"third"
will be replaced by other strings at any time. So using hardcoded NSRange values won't work.
I made a library that makes this a lot easier. Check out ZenCopy.
You can create Style objects, and/or set them to keys to reference later. Like this:
Then, you can easily construct strings AND style them AND have params :)
You can also style things easily with regex searches!
This will style all words with '@' in front of it with the 'token' style. (e.g. @jpmcglone)
I need to still get it working w/ everything
NSAttributedString
has to offer, but I thinkfontName
,fontSize
and color cover the bulk of it. Expect lots of updates soon :)I can help you get started with this if you need. Also looking for feedback, so if it makes your life easier, I'd say mission accomplished.
I think, it is a very convenient way to use
regular expressions
to find a range for applying attributes. This is how I did it:I was searching for a list of available attributes and didn't find them here and in a class reference's first page. So I decided to post here information on that.
Standard Attributes
Attributed strings support the following standard attributes for text. If the key is not in the dictionary, then use the default values described below.
NSAttributedString programming guide
A full class reference is here.
This solution will work for any length
I wrote helper to add attributes easily:
https://github.com/shmidt/MASAttributes
You can install through CocoaPods also :
pod 'MASAttributes', '~> 1.0.0'
Since iOS 7 you can use
NSAttributedString
with HTML syntax:You have to add the file "string.html" to you project, and the content of the html can be like this:
Now, you can use
NSAttributedString
as you want, even without HTML file, like for example:Source