Adding a Decoration View to a UICollectionView in Interface Builder

tl;dr: You Can’t. But…

My current project employs multiple UICollectionViews with custom layouts. Those layouts have a nice decoration view that I borrowed from Joe Keely and Kyle Richter (repo here), which puts a sleek, modern IKEA style ‘shelf’ behind the collectionView’s

Saweeet UIDecorationView
Saweeet UIDecorationView

cells (i.e., the ‘books’).

However, I kept getting an error, which the debugger translated as “You need to register your decoration view as a class or a nib, or prototype it in storyboard.” This, I was happy to do, except that storyboard does not provide decorationView protoyping, just header/footer views, and of course, the collectionViewCells themselves.

…you can register them in initWithCoder.

Imagine my surprise when despite all my efforts to register the durn view, Xcode was not in the least impressed. To make a long story short, I remembered that when initializing an object in Storyboard, initWithCoder is called (rather than init). I do not recall exactly which Apple docs gave me this nugget (please let me know in the comments), but I believe it was some chain of hyperlinks bouncing off NSCopying and NSCoder protocols.

In hindsight, there it is, clear as day, on SO. But duplication of answers to debug questions is (often) Good for the Internet, providing a larger bullseye for a questioner to hit. Happy Bug Hunting y’all!

…and we’re back!

UICollectionViews and I (part I)

tl;dr – one-line designated-init-boilerplate

If you take nothing else from this post, here is a clever LOC I encountered in Ash Furrow’s book on UICollectionViews:

Ok, on to the post (or skip to the summary):

First Thing: Apologies.

My apologies to you, my adoring audience and fans, during the unexpected and unexplained interruption. I cannot change your expectations, but I can provide an explanation: I switched web hosts to save $100, and learned much about the process in doing so. My biggest lesson (read “mistake from which I am determined to squeeze out something constructive”) was in regards to the WordPress Migration plugin.

Namely, I learned that It Exists! Never migrate by hand again; next time you are lost in the woods with your celebrity crush, and desperately need to find food, shelter, and to migrate your wordpress site, use this swiss army knife to look suave in front of your million dollar companion as you save the day!

Second Thing: Some Ash Furrow tips on UICollectionView

I have been working on an app for my portfolio that uses UICollectionViews, and ideally, needs a custom layout. This is a fun challenge, since it involves a bit more of my math background, but I really appreciate the tidbits an experienced dev throws in when showing you around a favorite piece of tech. Thus, I am going through Ash Furrow’s book on UICollectionViews, and thought to share some of the tidbits I picked up so far, halfway through.


  • XIBs and Storyboards are not really worth it for UICollectionViews, (with the possible exception of just having a blank one for the initialization code). Why?

“There are two problems with storyboards and collection views: the tight coupling between the collection view cell (its reuse identifier) and the code, and some tricky debugging when you modify the settings of the storyboard in code at runtime. You can’t rely on what you see visually at compile time because it’s likely going to be changed by code at runtime, anyway.” (Kindle Locations 834-836)

  • “[Use] custom UICollectionViewCell subclasses to keep your code loosely coupled; your view controller shouldn’t know about the internals of the cell’s view hierarchy.” (Kindle Locations 840-841)

Summary Conclusion

  • Clever 1-line init boilerplate.
  • WordPress Migration plugin for painless blog migration.
  • I’m knee-deep in UICollectionViews, and aim to present a recipe/tutorial on layouts soon, knock on wood.
  • Homage to Ash Furrow _|-\o_

Yet Another UI Demo App

“Libraries for Developers” UI demo app

This is an update/add-on to my earlier post about UI Controls apps. This app, like Cocoa Stars, is a ‘meta-app’, presenting and demo’ing a curated collection of third-party libraries or pods. I have found almost no overlap between the two apps, which is most impressive. You are able to ‘star’ and share links of the repos, which is very helpful, since I often find myself going through the demos like a catalogue, all at once, rather than seeking a specific solution for a given need. The PRO version costs $1, which I purchased to support the developer. Check it out!

Solutions: Making a Calculator (Adding Buttons to Numpad)

Adding Buttons to UIKit’s Numpad

Screen Shot 2015-08-20 at 10.49.21 AM
Xcode Statistician from the Scrivener team at Literature and Latte

On a current project, users need to enter their locations by latitude andlongitude. True, the real world use of such a feature is dubious (do you know, right now, your latitude and longitude to four digits? Or the lat/lng of your destination? Yes? Well, my response to you, dear reader, is STOP DRIVING while reading blogs!). However, to make a simple calculator — or even more basically, to enter a number and then Return — you will need more than the UIKit-provided numpad.


You want to make a vanilla calculator. You would like to enter numbers to a UITextField without the default alphanumeric keypad, but rather with a number pad. However, the UIKeyboardTypeNumberPad was “designed for PIN entry,” and just contains the digits.


Add a custom UIToolbar on top of the default Numpad with the button(s) you require.

How It Works

(This solution is but One of Many.)

UIToolbar, which normally appears at the bottom of the screen, can be added to the inputAccessoryView belonging to the UITextField in question. After wiring up the storyboard, we will: (more…)

Make Recipes of ALL The Projects!

An Argument to For Prolific Recipes From Everybody

Hello, Joe Programmer. Welcome to my blog. You have just finished writing your app for using whalesong to solve Fermat’s Last Theorem, or just finished your first program (Tic Tac Toe, right?). Doesn’t matter. Share it with the world.

This ocelot learned to code from recipes. No humans were harmed in the taking of this photo.

They will not thank you in your lifetime, but future generations of supermen/bots will praise your name or its binary equivalent for having hastened the coming of the wired future. What I’m saying is, even if you are not a teacher, not a job-seeker, or not even There Yet, share your code. But in a specific way. The way that is both Lazy and Helpful: Recipes.

What I’m saying is, even if you are not a teacher, not a job-seeker, or not even There Yet, share your code. But in a specific way. The way that is both Lazy and Helpful: Recipes.


What is a Recipe?

A recipe is code that is complete, bug-free, and can be compiled as is. It is code that is wrapped in a certain format, like so:

Title //write this last

Problem //1-3 sentences of a real or hypothetical problem

Solution //1-5 sentences of the approach, technique, or core “new” thing demonstrated by the code.

How It Works // (optional) This is not optional. Rather, when it is needed, it is necessary, but that isn’t always the case. This is the place where you explain ahead of time that line or two with the wonky syntax that even a read-through of the docs does not enlighten. Granted, if you need visuals (storyboard), you may be forced to upload a screenshot or two, but often this can be avoided through a few more sentences. Lift one pinky, or two?

…let’s be honest here – you already wrote this code. It is written. 95% of the work is done.

The Code //The magic sauce. All the hard work has been done before this. All that hard word in crafting a Title + 2-10 sentences will pay off, in that you have now prepared your reader for — let’s be honest here — a code dump. You already wrote this code. It is written. 95% of the work is done. You cut and paste it into a new project. You link it to github. You give it a one-over to prettify it (e.g., XAlign), delete all the distracting commented-out sections, and turn your terse comments into full sentences. That’s it. It’s done. Publish!

[Pro-Tip: This can be fulfilled with a very helpful ReadMe added to the code’s Github repo]

Why I Feel So Strongly About This

Implementation is so often the hardest part of any project. Students learn from the little things. “Oh, I see, @selector(someMethod:) has a colon because it takes an argument! That’s why my code has been broken for the last 3 hours! God bless you <#dear reader#>, bless you!” That sort of thing. The things that are so easy to overlook when you know it, but so hard to emulate when you do not.

Tutorials are hard to make. They are designed to hold someone’s hand and take them from point A to pointilliste Beta Prime. A recipe is easy. It rolls out of bed and into your blog, and the world is a better place. So do the right thing. Make the world a better place today. You descendent nanoboticles will thank you.

Open-Source UI Controls

Cocoa Controls on Your Device

Cocoa Controls: UI Elements for Hire

Perhaps the most powerful characteristic of knowledge is that it is relatively cheap (more specifically, it has a radically low marginal cost). Combine that with an open-source culture, and the result is that many wheels needn’t be reinvented. This is a heaven-sent boon for new developers, especially in the realm of UI and UX. As much as raster and vector graphics are on my list of mountains to conquer — and the principles of good design that make those packages useful — between Photoshop and UIKit, which do you think a babydev will prioritize? For many a beginner, this should be one less problem to deal with.

One very helpful site collecting various UI elements — with both free and paid code available — is Cocoa Controls. Give it a look over, and go nuts.

Do it one better: see the elements in action

For all that this website is an excellent resource, it is often hard to get a sense of how the elements work in action. Sometimes there are demo videos, more often flip-book gifs, but most often just static pictures. It’s also hard to get a ‘feel’ for the control in question. Although they are not so numerous, there are a few apps that help with this.

  1. Cocoa Stars – (Free), I cannot recommend this enough. You could get lost in the over 200 various controls on offer (mostly found on
    Cocoa Stars lets you test drive various UI elements right on your device.

    Github). While it certainly is not the end-all and be-all, it drastically lowers the barrier to entry, saving lots of time by letting you try out the controls on your device.

  2. NucliOS by Infragistics (free trial, copyrighted). This is a professional grade set of UI controls, with a professional grade price tag (starting at $899) – yet they provide their source code for you to peruse or copy, as a trial version. At the very least, it is a source of inspiration. [thanks to Omar Elfanek for discovering this]
  3. Dev Controls – (‘Free’ with copious ads and popups, grrr…). This app provides a curated list pointing to many UI Controls. Helpful, but not nearly as awesome as Cocoa Stars, which runs the controls it advertises. Still, this has over 1,000 elements to look through, and is a resource I am glad to have. And if the dev is truly spending time curating the list, then I forgive him the ads which support the endeavor.
  4. UI Tuner – (Free) – The iTunes description says it best:
      “This is a developers tool for designing, visualizing, and tweaking UI controls. Quickly change opacity, shadow orientation, transform parameters, just about any other visual property and see the result immediately on your iOS device. When you have your control tweaked just the way you want it, the app can email the source code to your Xcode system.” ++
  5. Cocoapods – (App Store link here [Free]). This is a helpful Cocoapods browser, but it doesn’t strictly run the pods’ demos on your device.

So all you new and experienced developers out there, you don’t have to reinvent the UIWheel! (You heard it here first 😉 )

 UPDATE (19 Aug 2015)

Also check out Libraries for Developers, another demo app like Cocoa Stars. (updated link can be found here).

Regular Expressions Can Solve Both Your Problems

In this post, we will:

  • Discuss/praise Regular Expressions in a cursory manner, but with enough quality links to get you started.
  • Provide an example of the power of RegEx (to validate a phone number).
  • Mini-Tutorial: Write a category on NSString to check if a string is a phone number, using NSRegularExpressions {iOS 8, Objective-C}.
  • Share jokes about regular expressions. Then we will laugh.

1. RegEx is a Powerful Tool worth adding to your Toolkit.

Others have defended the worth of RegEx used in moderation, so I won’t weigh down the internet by duplicating the substance of their arguments. This post aims to be first and foremost a tip-of-the-iceberg tutorial (feel free to skip to item #3). So although I will take it on faith that RegEx is a powerful tool, I feel compelled to make some semblance of a case for their newbie-friendliness. To wit, the unofficial bible of Regex’s  is Amazon’s #1 Best-seller!…in “FORTRAN Programming”. So let’s help the elephant exit the room, shall we?

Auchtung Elephants

There is a classic programming bon mot that goes like so:

Some people, when confronted with a problem, think:
“I know, I’ll use regular expressions.” Now they have two problems.

The reason for the knowing (nods|chuckles) from many of you in the audience is because, in the course of your career, you have encountered humor used to bleed off ‘regex anxiety’ (see the xkcd riffs here and here — no, really, come back when you’re done, I’ll wait), or else been force to scan such gems of brevity as this PERL-snippet of wisdom:

According to the poster of this string, this simply means to match any day of the year. It gets (irony alert!) a bit complex when you want to match that day by month, accounting for all the variations in month-length, adjusting for leap-years, and possible syntax variations like putting a space vs. a hyphen between significant figures. If you’re still with me, take heart: a regex doesn’t get much worse than that, so the hard part is over. Now the easy part.

(By the by, the guy who wrote the book on Regular Expressions [linked above], Jeffrey Friedl, did his darndest to trace that witticism; I betray my [pretensions to an] academic background by providing the link to that grand effort at proper attribution here.)

2. The Essence of RegEx in 10 Words:

RegEx is concise way of embedding logic into a search string. I’ll say it again: RegEx is concise way of embedding logic into a search string. That’s it.

RegEx is concise way of embedding logic into a search string. That’s it.

2 ex.

You are searching a (string →) data collection for the word ‘iambic’. But sometimes that word is at the beginning of a sentence. So you will accept both iambic  and Iambic .  Your logic may look like

Not too onerous. But what about checking if a string is a valid member of a class, say, a username? You have a number of rules for your username:

  • It can be any lower case letter, number, underscore, or dash…
  • …between 3 and 16 characters in length.

You could write out this:

Or you could use a regular expression like this (using the Regexer cocoapod):


3. Where To Get Started (Resources)

For ‘Structured Environment’ Learners:

  • A brand new CodeSchool intro course on RegExs, here (probably an hour or so of video, punctuated with interactive exercises called ‘challenges’; they’ve got a sense of humor, ++).
    • They also have a Ruby-centric screencast here.
  • Codecademy (not ‘Code Academy’, mind) has a JavaScript specific set of 10 exercises to get you up to speed, here.

For Unstructured Learners, there are many interactive tutorials (etc., etc.), walkthroughs, and playgrounds, books and graphic organizers (such as the following:


3a. Jokes

I love this list, with such gems as:

  • Some people, when faced with a problem, think, “I know, I’ll use #binary.” Now they have 10 problems.
  • Some people see a problem and think “I know, I’ll use #Java!” Now they have a ProblemFactory.

and a personal favorite…

  • Some people, wanting an escape from their full-time job, think “I know, I’ll contribute to open source.” Now they have two full-time jobs.

Please feel free to add links and original contributions in the comments.


Transcompilers and Interlinguistic Diplomacy

One of the most frequent questions asked by initiates into the profession is What language should I learn? This post…is not about that. Rather, it’s about transcompilers.

tl;dr – Why does this matter?

What is a transcompiler?

First, what is a regular compiler? A traditional compiler translates from a higher level of abstraction (e.g., Objective-C) to a lower level of abstraction (e.g., assembly or machine language). If a regular compiler can be thought of as ‘vertical’ translation, a transcompiler would be horizontal translation: it translates code from one language to another language of the same level of abstraction.

Screen Shot 2015-07-06 at 9.16.44 AM

It is very hard to write machine code directly. Humans overwhelmingly have some medium between us and the machine.
It is very hard to write machine code directly. Humans overwhelmingly have some medium between us and the machine.

One example is Coffeescript, a programming language that transcompiles into JavaScript, but has syntactic sugar inspired by Ruby among other languages. Wikipedia has a short and sweet example of how you can write something in one way, and have it compile natively as if it were written in a different way.

Where does Objective-C fit in?

Mostly, it doesn’t. This is because Objective-C has been developed more or less to support Apple devices, and the devices + language are more or less a one-to-one fit. However, often the tricky part of coding is not the UI, but the computations under the hood, aka business logic (I don’t only link to wikipedia, but I have found that, when it comes to All Things Code, it often is short, sweet, and to the point in an accessible way). Enter j2objc.

J2objC: Google’s Solution to a Shared Problem

J2objc is a script-based translator that converts Java source code into Objective-C source for iPhone/iPad applications. It is not an emulator, but outputs source code that can be built by XCode or Make, so the resulting apps run natively. My next post will be a non-methodical summary and highlight of descriptions I have found in the docs, and from a presentation (here) by the head of the project, Google’s Tom Ball. I have also been playing around with the tool, and will report any successes I have had. And if the gods smile on my efforts, I just may include a tutorial.

J2objC is not a cross-platform application tool. The source-code is compiled into object files, then linked up into an app. Your iOS device is running pure Objective-C. I will

tl;dr – Why does this matter?

This tool allows you to plug Java files into your Objective-C project. Java is still the #1 most popular programming language (by some metrics, at least), so collaboration can be made more easily. Java is also used for Android app development, and though it cannot be said that you could “write once, run anywhere”, it can automate much of the hassle of cross-development (e.g., the team at CodeName One, or these guys).

Principles of Object-oriented Programming: Why SOLID?

SOLID for Newbies

Future Principled Programmer

As a newly hatched programmer, comparing notes comes second nature to me. How can my code be more legible (but not verbose), elegant (but not clever), and defensive (but not paranoid)?

The easy rule of thumb passed down by my instructors has been “Make it work, make it right, make it fast”, a phrase that has been associated with a design paradigm that has come to be known as ‘agile software development‘ (and the wikipedia page). (see sidebar [under construction].

But the assumption underlying that phrase is that you will be refactoring multiple times. How can we make sure our code can even be refactored? The object-oriented programming  (OOP) paradigm can make things either worse or better by separating chunks of code into blocks of associated functionality. One of the nifty mnemonics for a series of ‘principles’ that guide in the right direction are what are known as The SOLID Principles of OOP.

SOLID Principles of OOP

S)ingle Responsibility Principle

“There should never be more than one reason for a class to change.”

Example: If your building closes a floor for renovations, you should only need to modify one class in your elevator’s program–and that the class should only need to be altered when floors are added or deleted.

That said, a word of caution: some programs are small, or simple, and it would be possible to subdivide endlessly for variations and potentialities that may never happen.

Open/Closed Principle

Classes/functions should be open for extension, but closed for editing/modification. It should be usable “as is”. Never modify them, just extend them.
Because it’s very messy, and would probably ruin the coat.

[credit: Betrand Meyer (1988).]

This is done by abstraction. E.g., a drawing class should not implicitly mean to draw with a black pen on paper. Rather, it should be to draw with something onSomethingElse. Then I could draw on paper, or even on nothing (maybe you want your SimPersons to do the wave, or dance to YMCA) through a simple extension overlaying the draw class.

Liskov Substitution Principle
Subtypes must be substitutable for their base-types.
Your Duck superclass will crash when it tries to fly the eDucky even though Batteries Not Included (for Ducks).

Technically, this can be expressed as:

Don’t introduce new behavior into a subclass that the base class couldn’t do.

E.g., you have a Bird Class, and a Duck subclass. Any Bird can fly with any Duck. But say you add a Penguin subclass.  A call to the [Bird fly] on a Penguin will crash your program, since Penguins cannot fly.

Without help, that is.


A cool corollary of this is that if you follow the LSP, you implicitly are adhering to the Open/Closed Principle. LSP => OCP

Interface Segregation Principle

Classes that implement interfaces should not be forced to implement methods they do not use.

Use small interfaces, not “fat” ones.

Reset and Write for streams, but not for Write-Only (Printers) or Read-Only (Screen).

Dependency Inversion Principle

a) High-level modules should not depend on low-level modules — both should depend on abstractions.
b) Abstractions should not depend on details – rather, details should depend on abstractions.

E.g., Xcode’s SVC depends on GIT? Bad. Xcode’s SVC uses GIT? Good.

Xcode –> SVC interface –> GIT

E.g., MVC.

We can test modules independently of each other. We can mock or fake interfaces to test the business logic.

Print {with logic x} to {appropriate source}

Print…to file…to PDF…to email client…to printer.

Helpful Unicode Characters

While the standard keyboard usually grants access to all the keys in regular use, and creates hotkeys for power use, in the middle lie the forlorn, neglected symbols. Symbols tap into an ancient and effective register for quick and immediate recognition, so they are especially appropriate to squeezing more functionality from said keyboard. Moreover, as a relative beginner in a class with other relative beginners, I find that communicating hotkeys and shortcuts is not as effective without the appropriate icons. So here they are, along with the unicode number needed to type them.

[How do you type unicode characters? Switch to the unicode hex input keyboard, then hold ⌥ + ???? and the icon magically appears!]

Source: obvious, no?

[How do you add the unicode hex input keyboard? See below.] By the by, you’ll often see these characters’ numbers preceded by & or # or x’s. They refer to the number’s base, and the character system used. So these characters are actually preceded by a Ux????. ‘U’ for unicode, and ‘x’ for hexadecimal.

Mac Special Key Icons and Unicode Number
 – F8FF
⌘ – 2318 – the Command Key symbol
⌥ – 2325 – the Option Key symbol
⇧ – 21E7 – the Shift Key (really just an outline up-arrow, not Mac-specific)
⎋ – 238B – the Escape Key (also not Mac-specific; described as “BROKEN CIRCLE WITH NORTHWEST ARROW”, or an escape character from ISO 9995-7).
And while we’re at it, some related (not mac-specific):
⇥ – 21E5 – the Tab Key symbol
⏎ – 23CE – the Return Key symbol
⌫ – 232B – the Delete Key symbol
⌽ – 233D – a possible substitute for the Power symbol
And even less used, but still common enough to merit Apple’s attention:
Mnemonic note: ALL the common arrow symbols are from 2190 to 21FF (list here), so play around, have fun!
← – 2190
↑ – 2191
→ – 2192
↓ – 2193…
⇞ – 21DE – Page Up symbol
⇟ – 21DF – Page Down symbol
Adding the Unicode-Hex Input keyboard

Go to Preferences  → KeyboardInput Sources and search for “Unicode”, and check the box.