views:

509

answers:

2

Hi - 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 it's 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 - its a lot of stuttering and book-keeping 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 implementation.
+2  A: 

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.

Rob Napier
I KNEW I had seen some reference to that before but I totally couldn't place it/re-find it. Thanks. Hmm, any suggestions regarding a harmless way to send something like a 'Name' to the code? Like maybe adding a 'Hint' in 'Accessibility' and then clearing it at runtime - or something like that?
JJ Rohrer
I could maybe pre-process the .xib file the Labels into, say, Hint.
JJ Rohrer
+1  A: 

Name is 100% not accessible after the object is loaded, something I always thought was odd too.

What is accessible is "tag", if you really want to access an element without defining an outlet you can set the (integer only) "tag" value, and then within the superview that holds the tagged element call viewWithTag: passing in the same integer. Don't forget the default is "0" so use something else.

Kendall Helmstetter Gelner