开发者

Adding actions to a button programmatically on iOS

开发者 https://www.devze.com 2023-03-01 14:14 出处:网络
I am trying to add an action to buttons which I am creating programmatically: [btnaddTarget:self action:@selector(indexAction)

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:UIControlEventT开发者_运维知识库ouchUpInside];

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;


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


tag is an NSInteger not NSInteger*

change to

NSInteger tid = ((UIControl*)sender).tag;


The way to do it is to set:

-(void)indexAction:(id)sender
{
NSLog(@"Tag=%@"[(UIButton*)sender tag]);
}

and the call:

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

not really sure about my casting, haven't tested that, but I think it should work! Best of luck.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号