Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to add a second tag to an UIbutton?

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.

like image 528
n.evermind Avatar asked Dec 16 '22 14:12

n.evermind


2 Answers

No you cant. Not directly at least. You can subclass UIButton and add another int property but that seems like an overkill for what you want..

I think it would be better to just decide on how you can fit both the values in the single tag integer...

e.g. if you have pageNumber and buttonNumber you can create the buttons tag like:

button.tag = pageNumber*100 + buttonNumber;

and when you want to which page a button belongs to or what is the index of a button on a page, you can dacode the tag:

int pageNum = button.tag /100;
int buttonNum = button.tag % 100;
like image 175
Swapnil Luktuke Avatar answered Dec 21 '22 23:12

Swapnil Luktuke


  • Create a subclass of UIButton with your second tag declared as property.

  • You could as well create an array to map the tag of your button to a page, which would prevent creating a subclass but will introduce some array management method.

I'd prefer the array solution, as I try to prevent subclassing whenever I can.

like image 25
Nick Weaver Avatar answered Dec 22 '22 01:12

Nick Weaver