Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding actions to a button programmatically on iOS

I am trying to add an action to buttons which I am creating programmatically:

        [btn    addTarget:self
            action:@selector(indexAction)
     forControlEvents:UIControlEventTouchUpInside];

This works fine. However, I now want to pass a variable (int k) to the indexAction method. I couldn't get this to work:

        [btn    addTarget:self
            action:@selector([self indexAction:k])
     forControlEvents:UIControlEventTouchUpInside];

I am sure I'm doing something wrong. This is the context of the above code:

  -(void) initIndexButtons {

    float buttonPadding = -8;
    float buttonWidth = 23;
    float buttonHeight = 80;
    CGRect frame = CGRectMake(0,0,0,0);
    for (int k=0;k<5;k++)
    {
        UIButton* btn = [[UIButton alloc] initWithFrame:frame];;        btn.tag = k;
        btn.frame = CGRectMake(0, k*(buttonPadding+buttonHeight), buttonWidth, buttonHeight);

        UIImage *newImage = [UIImage imageNamed:@"index.png"];
        [btn setBackgroundImage:newImage forState:UIControlStateNormal];

        [btn    addTarget:self
                action:@selector(self indexAction:k)
         forControlEvents:UIControlEventTouchUpInside];
    }
}

-(void)indexAction:(int *)buttonTag
{
    NSLog(@"buttonTag: %i", buttonTag);
}

EDIT:

I changed my code to:

// ...
[btn    addTarget:self
                action:@selector(indexAction:)
         forControlEvents:UIControlEventTouchUpInside];

        //[self indexAction:k];

        [indexView addSubview:btn];
        [indexView sendSubviewToBack:btn];
    }
}

-(void)indexAction:(id)sender
{
    NSInteger *tid = ((UIControl *) sender).tag;
    NSLog(@"buttonTag: %i", tid);
}

But now I get the warning message that "Initialisation makes pointer from integer without a cast for the line NSInteger *tid = ((UIControl *) sender).tag;


EDIT:

This is the right line of code:

NSInteger tid = ((UIControl*)sender).tag;
like image 562
n.evermind Avatar asked Apr 28 '11 16:04

n.evermind


2 Answers

Normally the method that a button calls takes one parameter:

(id)sender

Take a look at the question - how to pass a variable to a UIButton action

like image 55
Brian Avatar answered Sep 26 '22 01:09

Brian


tag is an NSInteger not NSInteger*

change to

NSInteger tid = ((UIControl*)sender).tag;
like image 37
tidwall Avatar answered Sep 26 '22 01:09

tidwall