Jignesh Fadadu
Jignesh Fadadu

Reputation: 409

Set Buttons' Background randomly from array of images

else if (setIndexPath == 4)
{
    viewWithButtons.frame = CGRectMake(5, 40, 310, 390);

    int ch = 6;
    int cv = 6;

    for ( int i = 0 ; i < cv ; ++i )
    {
        for ( j = 0 ; j < ch ; ++j )
        {
            btnMatrix = [[[UIButton alloc] initWithFrame:CGRectMake(10+pw*j, 51+ph*i, width, height)] autorelease];
            btnMatrix.tag = i*ch+j;
            btnMatrix.userInteractionEnabled = TRUE;
            [btnMatrix addTarget:self action:@selector(changeImage:) forControlEvents:UIControlEventTouchDown];
            [btnMatrix setBackgroundImage:imgDefaultBG forState:UIControlStateNormal];

            [viewWithButtons addSubview:btnMatrix];

            [arrButton addObject:btnMatrix];
        }
    }
}
[self.view addSubview:viewWithButtons];

I am generating buttons dynamically according to the selected matrix, like 4 * 4, 4 * 5, 4 * 6, 5 * 6, 6 * 6 etc....

Buttons are completely set as per the selected matrix from above (the code is for 6 * 6 matrix).

Now i have to set random background images of these buttons.

I am not able to set this kind of dynamic buttons' background.

is there any effective way to set backgrounds dynamically in random order for each separate buttons?

    for (intimg = 1; intimg <= 15; intimg++)
    {
        arr_FirstSet = [[NSMutableArray alloc] initWithObjects:[NSString stringWithFormat:@"%d_f_2.png",intimg], nil];
    }
    for (intimgSET2 = 1; intimgSET2 <= 15; intimgSET2++) {
        arr_SecondSet = [[NSMutableArray alloc] initWithObjects:[NSString stringWithFormat:@"%d_s_2.png",intimgSET2], nil];
    }

I am adding images in this format to the NSMutableArray.

How to pick random image from the above used arrays. I have to match both arrays images & give the result on buttons. If both matches, suppose i press on one button it will display 1_f_2.png & on another button press it will display 1_s_2.png (as background)then both of these buttons will be removed from the view.

I had tried many logics to get this.

I am not getting exactly what i am interested to do on touchdown of button.

Please suggest any code snippet or link or code also.

Thanks in advance.

Upvotes: 0

Views: 531

Answers (1)

Konrad77
Konrad77

Reputation: 2535

- (UIImage*)randomImage {
    NSInteger imageCount = [[self imageArray] count]
    return [[self imageArray] objectAtIndex:arc4random() % imageCount]; 
}

If you want matching pairs. Use dictionary with two images, or simple class holding two images.

Upvotes: 1

Related Questions