[英]iOS Detecting Index of UIButton Press Dynamic
因此,基本上我在进行API调用以检索慈善机构列表。 然后,将所有这些放置在数组中并动态设置UIButtons。
然后,我允许用户选择慈善机构并显示带有该索引数据的视图。
我的循环在这里;
for (int i = 0; i < [self.imageArray count]; i++) {
NSDictionary *listRoles = [self.imageArray objectAtIndex:i];
NSString *charityName = [listRoles objectForKey:@"name"];
NSString *charityDescription = [listRoles objectForKey:@"description"];
NSString *charityImage = [listRoles objectForKey:@"image"];
UIImage *pImage=[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:charityImage]]];;
UIButton *button = [[UIButton alloc] initWithFrame:frame];
[button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[button setImage:pImage forState:UIControlStateNormal];
[button setTag:i];
[self.scrollView addSubview:button];
然后,我有了一个单击的方法;
- (void)buttonClicked:(UIButton*)button
{
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle: nil];
CharityProfileViewController *cpvc = [storyboard instantiateViewControllerWithIdentifier:@"CharityProfile"];
[self presentViewController:cpvc animated:YES completion:nil];
}
我如何检索索引,我知道我可以为UIButton设置随机标签,但是我怎么仍会知道哪一个呢?
您可以将button的标记值设置为
[button setTag:i+1];
然后在按钮动作
- (void)buttonClicked:(UIButton*)button
{
NSLog(@"Button Tag : %d",button.tag);
NSLog(@"Selected Index Object : %@",[self.imageArray objectAtIndex:button.tag-1]);
}
您可以通过button.tag
检索按钮的标记,也可以将按钮添加到数组中,然后在buttonClicked:
方法中使用[buttonsArray indexOfObject:button]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.