views:

30

answers:

2

What is the best way when setting up a UI for the iPhone to differentiate between multiple items of the same type (i.e. 2 sliders) currently I am assigning the controls unique "tags" and then querying them in Xcode. Is this the way to go or am I missing something else?

-(IBAction)switchChanged:(UISwitch*)senderSwitch {
    if([senderSwitch tag] == 1) {
        NSLog(@"SwitchChanged: Engines");
    }
    ...

gary

+3  A: 

Hey Gary! I usually choose similar approach, though I prefer using integer constants instead of 'raw' numbers. Here's an example:

const int VIEW_TAG_A_SWITCH = 1;
const int VIEW_TAG_OTHER_SWITCH = 2;

- (IBAction)switchChanged:(UISwitch*)senderSwitch {
    switch (senderSwitch.tag) {
        case VIEW_TAG_A_SWITCH:
            // do something
            break;
        case VIEW_TAG_OTHER_SWITCH:
            // do something else
            break;
    }
}

This makes code more informational and help you to deal with situations when you need to change the UIView tag value for some reason (this way you only change it once in your nib and once in your code).

It's also very handy to use enums when you need to work with a group of controls. Here's a dummy single selection group of buttons example (something similar to what <input type="option" />):

enum GenderOptionButtons {
    kMaleGenderOptionButton = 10,
    kFemaleGenderOptionButton,
    kUndefinedGenderOptionButton,
    NUM_GENDER_OPTION_BUTTONS
}

- (IBAction)buttonDidTouchUpInside:(UIButton *)senderButton {
    for (int i = kMaleGenderOptionButton; i < NUM_GENDER_OPTION_BUTTONS; i ++) {
        [(UIButton *)[self.view viewWithTag:i] setSelected:NO];
    }

    senderButton.selected = YES;
}
Ivan Karpan
I use an `enum` for similar purposes. It works great and makes tags easier to maintain.
Alex Reynolds
Thanks Ivan, just so I am clear the enum declaration would go in the *.h file right?
fuzzygoat
It depends on what you actually need. For local usage it quite enough to simply declare/define enums within implementation (.m) file.
Ivan Karpan
Thanks Ivan, *.m was actually where I ended up putting it this time as it seemed more of an implementation detail.
fuzzygoat
+1  A: 

If you don't own direct reference (i.e. IBOutlet) to controls, then the "tag" approach is ok.

One advantage of this approach is that you can have different kind of controls calling the same action method. One major drawback of this approach is you have to keep in sync the tags between IB and XCode.

Laurent Etiemble