I’m contemplating writing some helper functions to make it easier to do simple changes to the UI elements in my iPhone NIB. Mainly – I want to access a UILabel, or other element, via its Name in Interface Builder. Is this possible? Is there a smarter approach?
Example
Say I want to make a super simple iPhone app that displays ‘Hello World’. I start a new project and then open the NIB and drag a UILabel into my view and give it a ‘Name’ of ‘LblMain’. Now, presuming that I’ve included my handy helper function, I’d like to assign the label some new text something like this:
[helper setText:@"Hello World" forLabel:@"LblMain"];
-or-
UILabel *ObjTmp = [helper getUILabel:@"LblMain"];
ObjTemp.text = @"Hello World";
Now – the trick is that I didn’t add a:
IBoutlet UILabel *ObjLblMain;
anywhere in .h file – I’m just accessing that label dynamically – wouldn’t that be nice?!
Now, for simple apps, to add some more labels or images, I could drag them into my NIB, assign them names in that element’s inspector window, and then immediately access them inside code without the stuttering & hassle of adding them in the .h file.
Motivation
- Basically, I’m frustrated that I have to wire every element in my NIB – it’s a lot of stuttering and bookkeeping that I’d rather avoid.
- I could give a design some naming conventions, and they could generate a NIB without needing to be intimate with the implementation.
You can definitely load the NIB programmatically, find all the objects and query them to work out what points to what. Just look at Loading Nib Files Programmatically. But the problem is that the Interface Builder Identity Name isn’t exposed outside of IB. So I’m not sure what you would use as the “forLabel” parameter. The “Name” field is just a convenience for the IB document window. It’s not a property on
NSObject.