Aleks G
Aleks G

Reputation: 57326

Refer to UIView by its name in a variable

In my UIViewController descendant, I have a set of four "blocks". Each "block" is a UIView four children: two UILabel's, one UIImageView and one UIView. All of these are created in interface builder and are connected to the class using IBOutlet's.

In my class, I have corresponding members:

IBOutlet UIView      *block1;
IBOutlet UILabel     *title1;
IBOutlet UILabel     *text1;
IBOutlet UIImageView *image1;
IBOutlet UIView      *separator1;

IBOutlet UIView      *block2;
IBOutlet UILabel     *title2;
IBOutlet UILabel     *text2;
IBOutlet UIImageView *image2;
IBOutlet UIView      *separator2;

IBOutlet UIView      *block3;
IBOutlet UILabel     *title3;
IBOutlet UILabel     *text3;
IBOutlet UIImageView *image3;
IBOutlet UIView      *separator3;

IBOutlet UIView      *block4;
IBOutlet UILabel     *title4;
IBOutlet UILabel     *text4;
IBOutlet UIImageView *image4;
IBOutlet UIView      *separator4;

I'm getting the data to be set into these UIViews dynamically - and it's always in a set of four, so the initialisation of each block is the same. Ideally, I'd like to do something like this:

Block *block;
UIImage *img;

for(int i=1; i<=4; i++)
{
    block = [response blockNumbered:i];

    [<"title"+i> setText:[block getTitle]];
    [<"text"+i> setText:[block getText]];
    img = [block getImage];
    if(img)
    {
        [<"image"+i> setImage:img];
    }

    [<"separator"+i> setHidden:![block needSeparator]];
}

(Note that this is simplified code, in real life, there's a lot more to this initialisation, closer to 200 lines code for each of the four blocks - but exactly the same logic.) Now, if I could only somehow refer to a view having the name in a string variable!..

Is there any way to achieve this?

P.S. I know I can create all these views in the code as an array of corresponding views, however then I'd have to do the layout in the code as well - and I'd rather do this in IB. Or is there any way to declare an array of UIViews's as IBOutlet and connect each element in the array in IB?

Upvotes: 1

Views: 2162

Answers (2)

sch
sch

Reputation: 27516

You can use valueForKey::

[[self valueForKey:[NSString stringWithFormat:@"title%d", i]] setText:[block getTitle]];

Upvotes: 3

Saurabh Passolia
Saurabh Passolia

Reputation: 8109

you should think of modifying your logic a bit and make it dependent on tagging. You can tag all subviews like subview1.tag = 1001; subview2.tag = 1002; later on you can iterate all subviews on tag values.

Upvotes: 0

Related Questions