How can I programmatically access UI elements in a NIB without 'wiring' them?

JJ Rohrer picture JJ Rohrer · Feb 18, 2010 · Viewed 16.4k times · Source

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.

Answer

Kendall Helmstetter Gelner picture Kendall Helmstetter Gelner · Feb 18, 2010

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.