为 UIButton 添加目标 - iOS
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11939772/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Add target for UIButton - iOS
提问by Siddharthan Asokan
Anyoone can help me on how to add action to call the following method using UIButton
.
任何人都可以帮助我了解如何添加操作以使用UIButton
.
-(void)navigatePics:(id)sender andIndex:(NSInteger *)index{}
回答by CSmith
Use the button.setTag:(NSInteger) method to add the index to the UIButton as a tag.
使用 button.setTag:(NSInteger) 方法将索引作为标签添加到 UIButton 中。
UIButton *button = ...;
[button setTag:1234];
[button addTarget:self action:@selector(navigatePics:) forControlEvents:UIControlEventTouchUpInside];
Then in navigatePics, read the tag.
然后在navigatePics 中,读取标签。
-(void)navigatePics:(UIButton *)sender
{
int index = sender.tag;
// index = 1234;
}
回答by Tomasz Dubik
UIButton *button = [[UIButton alloc] init];
button.tag = 4; //index
[button addTarget:self @selected(buttonDidTap:)];
...
[button release];
-(void)buttonDidTap:(UIButton *)sender{
NSInteger index = sender.tag;
}
回答by John Corbett
This should do the trick. Don't use self if you want to call this method on another instance. In that case, just use that instance in place of self.
这应该可以解决问题。如果要在另一个实例上调用此方法,请不要使用 self。在这种情况下,只需使用该实例代替 self.
[button addTarget:self action:@selector(navigatePics:andIndex:) forControlEvents:UIControlEventTouchUpInside];