Attributed String and Regular Expressions (RegEx). Full Stop. These two things have been occupying my mind for the first 3 weeks of our final project at iOS Bootcamp with The App Academy, and its been a love hate relationship. I will admit mostly hate in the beginning, but eventually (like most things) it becomes more clear the more you work on it. This is a too short article to explain this in full. Hopefully I can make a nice tutorial soon.
So what do I mean when I say: how to make text look good? Take an example of a ToDo-list:
Displaying this in with a String in a Label is not so difficult of course. But what if you want to make this ToDo-list visualise the items on it differently, for example like this:
This is a bit trickier to display in a Label with a String. This is where attributed strings comes in. An attributed string is a string can hold attributes for individual words and characters. With attributes I mean font size, background color, font color, font type, underlining etc. The easy recipe for doing this is as follows:
Doesn’t sound too difficult right? And it doesn’t have to be if you are only attributed one or two string. Then you can manually set the different attributes to the different ranges as you want. But if you want to automate this process so you can use it with multiple string, then it gets more complicated. For example if you want every word that is surrounded by *’s, for example *Get a job*, to be red and bold, then you need to have a way of searching the string for those *. This is where regular expressions come in. Regular expressions is a sequence of symbols and characters expressing a string or pattern to be searched for within a piece of text. This is too complicated to explain in one small article, but I’ll post some links to some good tutorials and websites that explains it better. Basically you can say use an expression that searches for *Important* then adds an attribute to that search result. The regular expression for this would be simply (*Important*), but this is pretty easy. Other examples of regular expressions are:
So you can see it can become quite complex, but there is also so much you can do with them. So the easy recipe from before now becomes a bit more advanced:
Instead of adding attributes to the matches you can also for example search and replace word within a string. For some more explanation about this look at these websites: http://www.regexpal.com/ is an easy tool to test out regular expressions to see if you can match what you are looking for. NSRegularExpression Tutorial and Cheat Sheet and NSRegularExpression Tutorial: Getting Started at Ray Wenderlich is a good place to start to learn about attributed strings and regular expressions
0 Comments
Leave a Reply. |
Archives
April 2016
Categories
All
|