2015-04-21 116 views
1

我在UIButton (Add Item Button)的操作方法中創建了UILabel (lblCount)UIButton (btnAdd)。新的UILabelUIButton被添加到scrollviewUILabel (lblCount)顯示計數UIButton (btnAdd)點擊。這裏,addBtnClickCount是一個計數點擊次數的整數。訪問在運行時創建的UILabel

UILabel * lblCount = [[UILabel alloc] initWithFrame:CGRectMake(50, 100*addBtnClickCount, 25, 25)]; 
    lblCount.text = [NSString stringWithFormat:@"%d",count]; 
    lblCount.tag = addBtnClickCount; 
    lblCount.textColor = [UIColor whiteColor]; 
    lblCount.textAlignment = NSTextAlignmentCenter; 
    [self.scrollView addSubview:lblCount]; 

    addBtnClickCount = addBtnClickCount+1; 

將有多個label (lblCount)button (btnAdd)當用戶點擊Add Item按鈕。我想訪問特定的label,特別是add buttondisplay the count

回答

2

您已經設置標籤在標籤上。創建一個可變數組labelarray併爲其添加標籤。要訪問特定標籤,請在添加按鈕的操作上執行以下代碼。

 -(void)addItem:(UIButton*)button{ 
      UILabel* lblShowCount = [_labelArray objectAtIndex:[button tag]]; 
      lblShowCount.text = [NSString stringWithFormat:@"%d", [lblShowCount.text integerValue]+1]; 

     } 
1

你應該有一個數組,你可以添加標籤和按鈕(這可能是一個包含字典或自定義類或多個數組的數組)。現在,當點擊一個按鈕時,您可以找到它在陣列中的位置並獲取相應的標籤進行更新。

作弊方式是設置按鈕和標籤的tag,以便您可以使用viewWithTag:找到另一個。

0

您需要在創建標籤和按鈕時設置唯一的tag值,並使用viewWithTag:您可以訪問相應的UI容器。

2

在這裏,我明白@Hem Poudyal,知道在viewWithTag的幫助下,他會得到輸出。但不知道如何實現。所以我在這裏描述。

步驟1:我在這裏加入UILabelUIButtonself.view到代替UIScrollView。我希望你可以將它轉換爲UIScrollView。這裏我申請了UILabel tagUIButton tag之間的一些關係。你可以在下面的代碼中看到。

for (int i=0; i<10; i++) { 

     UILabel * lblCount = [[UILabel alloc] initWithFrame:CGRectMake(50, (i*50)+((i+1)*5), 100, 50)]; 
     lblCount.text = [NSString stringWithFormat:@"%d",0]; 
     lblCount.tag = [[NSString stringWithFormat:@"%d%d",i,i] integerValue]; 
     lblCount.backgroundColor = [UIColor yellowColor]; 
     lblCount.textAlignment = NSTextAlignmentCenter; 
     [self.view addSubview:lblCount]; 

     UIButton* btnTemp = [UIButton buttonWithType:UIButtonTypeCustom]; 
     btnTemp.tag = i; 
     btnTemp.backgroundColor = [UIColor redColor]; 
     [btnTemp addTarget:self action:@selector(btnTempClick:) forControlEvents:UIControlEventTouchUpInside]; 
     btnTemp.frame = CGRectMake(150, (i*50)+((i+1)*5), 100, 50); 
     [btnTemp setTitle:[NSString stringWithFormat:@"Button : %d",i] forState:UIControlStateNormal]; 
     [self.view addSubview:btnTemp]; 
    } 

第2步:在UIButton選擇器方法中,執行以下操作。

-(IBAction)btnTempClick:(id)sender{ 
    UIButton* btnInner = sender; 

    NSInteger lblTagbaseOnButtonTag = [[NSString stringWithFormat:@"%ld%ld",btnInner.tag,btnInner.tag] integerValue]; 
    UILabel* lblReceived = (UILabel*)[self.view viewWithTag:lblTagbaseOnButtonTag]; 
    lblReceived.text = [NSString stringWithFormat:@"%ld",[lblReceived.text integerValue]+1]; 
} 

和輸出端:

enter image description here