2013-12-16 39 views
1

所以基本上我做了一個API調用來檢索慈善列表。然後我將所有這些放在一個數組中並動態設置UIButtons。iOS檢測索引的UIButton按動態

然後,我允許用戶選擇慈善機構並使用該索引的數據顯示視圖。

我的循環在這裏;

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設置隨機標籤,但我怎麼會仍然知道哪一個?

+0

使用標籤你可以得到索引 –

+0

你已經設置了UIB的標籤屬性utton。你可以很容易地找到button.tag .. –

回答

2

可以設置按鈕的標籤值

[button setTag:i+1]; 

然後進入按鈕動作

- (void)buttonClicked:(UIButton*)button 
{ 
    NSLog(@"Button Tag : %d",button.tag); 

    NSLog(@"Selected Index Object : %@",[self.imageArray objectAtIndex:button.tag-1]); 
} 
+0

這工作!神奇的小反應! :) –

0

您可以通過button.tag檢索您的按鈕,標籤或添加按鈕的數組,並在你的buttonClicked:方法使用,然後[buttonsArray indexOfObject:button]