Hem Poudyal Hem Poudyal - 3 months ago 7
iOS Question

Accessing UILabel created on run time

I have created

UILabel (lblCount)
and
UIButton (btnAdd)
on a
UIButton (Add Item Button)
's action method. The new
UILabel
and
UIButton
is added to
scrollview
. The
UILabel (lblCount)
shows count of
UIButton (btnAdd)
tapped. Here,
addBtnClickCount
is an integer which counts the number of click.

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;


There will be multiple
label (lblCount)
and
button (btnAdd)
when user taps Add Item Button. I want to access particular
label
for particular
add button
and
display the count
.

Answer

You have already set tag on your label. Create a mutable array labelArray and add label to it. To access the particular label do following code on add button's action.

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

         }
Comments