我正在尝试向我以编程方式创建的按钮添加操作:
[btn addTarget:self
action:@selector(indexAction)
forControlEvents:UIControlEventTouchUpInside];
这很好用。但是,我现在想要将一个变量(int k)传递给indexAction方法。我无法解决这个问题:
[btn addTarget:self
action:@selector([self indexAction:k])
forControlEvents:UIControlEventTouchUpInside];
我确信我做错了什么。这是上述代码的上下文:
-(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);
}
编辑:
我将代码更改为:
// ...
[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);
}
但是现在我收到警告消息“初始化从整数中生成指针,而没有针对行NSInteger *tid = ((UIControl *) sender).tag;
的强制转换
编辑:
这是正确的代码行:
NSInteger tid = ((UIControl*)sender).tag;
答案 0 :(得分:3)
答案 1 :(得分:2)
tag
是NSInteger
而不是NSInteger*
更改为
NSInteger tid = ((UIControl*)sender).tag;
答案 2 :(得分:1)
这样做的方法是设置:
-(void)indexAction:(id)sender
{
NSLog(@"Tag=%@"[(UIButton*)sender tag]);
}
和电话:
[btn addTarget:self
action:@selector(self indexAction:)
forControlEvents:UIControlEventTouchUpInside];
}
对我的铸造不太确定,没有测试过,但我认为它应该有效! 祝你好运。