I was wondering if it is possible to add a second tag to a UIButton? I’ve created a number of buttons programatically in a for-loop and need a reference to the number of the button (e.g. 0, 1, 2) and another reference (integer) in which I store a reference to the page the button links to (e.g. 22, 30, 49). The numbers are not related so I can’t determine the first through the second.
This is what I’d like to have:
for (int k=0; k < numberOfTabs; k++) // k < 4 (e.g. 3 < 4)
{
UIButton* btn = [[[UIButton alloc] initWithFrame:frame] autorelease];
btn.tag = k;
btn.tag2 = someReference;
btn.frame = CGRectMake(-10, 0, buttonWidth, buttonHeight);
[btn addTarget:self
action:@selector(tabAction:)
forControlEvents:UIControlEventTouchUpInside];
[btn addTarget:self
action:@selector(tabDelete:)
forControlEvents:UIControlEventTouchDragOutside];
/...
Any suggestions would be very much appreciated.
Why not store the second (any more, if needed) parameters in something like an NSMutableArray?
You can get your page number at any time by simply indexing into the button_to_page array.
You can also search the array for a page number and get the button index (if needed).
Now, having said that, here you are creating a new NSNumber object for each button’s page tag and also carrying around an NSMutableArray to boot. I really think that subclassing UIButton is the way to go. I don’t like the idea of encoding stuff into the single tag unless there’s a real compelling reason. If you subclass you are still keeping the UIButton pretty lightweight and all your data is encapsulated within the same object very cleanly:
MultiTag_UIButton.h
MultiTag_UIButton.m
It really is that simple, you don’t have to write any code, just add the page property and you are off to the races. Then you can do this:
Clean and simple. Realistically you’d have to do a little more in the new class, but you get the idea.