Nasir Khan
Nasir Khan

Reputation: 881

Button tag not working with Dynamic Value in a loop?

Kindly check my code:

for (i = 0; i < fifth_img.count; i++)
{
    UIButton *aButton = [UIButton buttonWithType:UIButtonTypeCustom];
    aButton.frame     = CGRectMake(xCord, yCord + space,buttonWidth,buttonHeight);
    [aButton addTarget:self action:@selector(whatever1:) forControlEvents:UIControlEventTouchUpInside];
    [aButton setTitle:[NSString stringWithFormat:@"%d",(int)i] forState:UIControlStateNormal];
    aButton.titleLabel.font = [UIFont systemFontOfSize:0.0];

    aButton.tag = i;
    [aButton setBackgroundImage:[UIImage imageNamed:[fifth_img objectAtIndex:i]] forState:UIControlStateNormal];
    [seasonsScrollView addSubview:aButton];
    yCord += buttonHeight + space;
}
[seasonsScrollView setContentSize:CGSizeMake(Vu_leftPanel.frame.size.width, yCord)];
[Vu_leftPanel addSubview:seasonsScrollView];


for( int b=0; b<6; b++){
    [(UIButton *)[Vu_leftPanel viewWithTag:b] setBackgroundImage:[UIImage imageNamed:[fifth_img objectAtIndex:b]] forState:UIControlStateNormal];
}

When i put 5 or 3 or 1 in viewWithTag:5 it's working but when i put just b, the app crash.

Upvotes: 2

Views: 324

Answers (2)

Vikas Dadheech
Vikas Dadheech

Reputation: 1720

Make sure that Vu_leftPanel does not have any other view with the tag between 0 and 6 [As the default tag for the views is 0]. As setBackgroundImage: forState: method can only be called on UIButton. If any other view receives this method call, then app will crash with unrecognized selector sent to instance exception.

Try setting the tags from 1000 to 1006. And then try setting the background image.

Upvotes: 3

Nimit Parekh
Nimit Parekh

Reputation: 16864

int xCord = 0;
    int yCord = 0;
    int space = 5;
    int buttonWidth = 25;
    int buttonHeight = 25;
    for (int i = 0; i < 5; i++)
    {
        UIButton *aButton = [UIButton buttonWithType:UIButtonTypeCustom];
        aButton.frame     = CGRectMake(xCord, yCord + space,buttonWidth,buttonHeight);
        [aButton addTarget:self action:@selector(whatever1:) forControlEvents:UIControlEventTouchUpInside];

        [aButton setTitle:[NSString stringWithFormat:@"%d",(int)i] forState:UIControlStateNormal];
        aButton.titleLabel.font = [UIFont systemFontOfSize:0.0];

        aButton.tag = 1000 + i;
        [aButton setTitle:[NSString stringWithFormat:@"%i",1000 + i] forState:UIControlStateDisabled];
        [aButton setBackgroundImage:[UIImage imageNamed:[fifth_img objectAtIndex:i]] forState:UIControlStateNormal];
        [seasonsScrollView addSubview:aButton];
        yCord += buttonHeight + space;
    }
for( int b=0; b<6; b++){
        [(UIButton *)[Vu_leftPanel viewWithTag:1000 - b] setBackgroundImage:[UIImage imageNamed:[fifth_img objectAtIndex:b]] forState:UIControlStateNormal];
    }

Upvotes: 1

Related Questions