Ooh, ooh, look - shiny things!

RubyMotion and Interface Builder…

May 7th, 2012

…sitting in a tree, K-I-S-S-I-N-G…

So, all of the cool kids have been talking about Laurent Sansonetti’s next project: RubyMotion, a port of MacRuby targeted at iOS. On the whole I’m pretty impressed with what you can already do with it. One of the issues that people having been mentioning though, is that you lose the ability to use Interface Builder with it, but this isn’t actually true!

Here I’m going to show you how to work with Interface Builder, I’ll base the project off the one used in the Pragmatic Studio screencast (the icon and background images come from there as well, by the way).

Update: the images don’t dome from there any more! The images used in the screencast are from iStockPhoto, so I’ve replaced the background image with a different one. Needless to say this doesn;t affect any of the code.

Setting up a Project

Start off as normal: motion create MagicBallDemo. In the project folder create a new subfolder called interfaces, this is where all of the .xib files will be saved.

Next create a model class called MagicBall and a view controller called MagicViewController which extends UIViewController, also create a file to store some small helper methods called helpers.rb. Don’t worry about the contents of these files for now, I’ll come back to them, but you should have the following:

Creating the User Interface

Open Xcode and hit ⌘-N to create a new file, select the Empty template and save the file into the folder you just created. Now add a View Controller from the object library and set the custom class to MagicViewController; you can’t edit this field directly but you can paste into it, so select the class name from app/magic_view_controller.rb.

The next step is to add the view to it’s controller, normally this would just mean dragging a UIImageView on top of the controller but that won’t work here. There is a problem with interface builder in that you can’t add subviews to UIImageViews, which is a pain in the ass. A simple workaround is described in this Stack Overflow question, and that’s what we’ll do here. So, add a UIView to the view controller and set it’s custom class to be UIImageView (which should be available in the pick-list). You can’t set the image here, that will need to be done in code.

Finally add the label and configure it as desired. Save your changes and close XCode.

You can compile this into a .nib using ibtool, this script will compile all of the interfaces in your project (just one in this case):