Search code examples
iphoneobjective-ciosuibuttonnsarray

Programmatically setting the image of a UIButton based on the image stored at a specific index in an NSArray


Difficult to explain this question. I am attempting to create a set of UIButtons on screen which is based on the number of entries in an NSArray. I have created an NSArray containing a number of images, like so:

socialArray = [[NSArray alloc] initWithObjects:
                   [UIImage imageNamed:@"FacebookButton.png"],
                   [UIImage imageNamed:@"WebsiteSocialButton.png"],
                   [UIImage imageNamed:@"TumblrButton.png"],
                   [UIImage imageNamed:@"TwitterButton.png"],
                   [UIImage imageNamed:@"InstagramButton.png"],
                   [UIImage imageNamed:@"VimeoButton.png"],
                   [UIImage imageNamed:@"GooglePlusButton.png"],
                   [UIImage imageNamed:@"YouTubeButton.png"],
                   [UIImage imageNamed:@"PinterestButton.png"],
                  nil];

and am creating the number of items in the view based on that, like so:

- (NSUInteger)numberOfItemsInCarousel:(iCarousel *)carousel
{
    return [socialArray count];
}

I am then programatically creating the button and setting its image, like so:

- (UIView *)carousel:(iCarousel *)carousel viewForItemAtIndex:(NSUInteger)index reusingView:(UIView *)view
{ 
    UIButton *button = (UIButton *)view;
    if (button == nil)
    {
        //no button available to recycle, so create new one
        UIImage *image = [UIImage imageNamed:@"page.png"];
        button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(0.0f, 0.0f, image.size.width, image.size.height);
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [button setBackgroundImage:image forState:UIControlStateNormal];
        button.titleLabel.font = [button.titleLabel.font fontWithSize:50];
        [button addTarget:self action:@selector(buttonTapped:) forControlEvents:UIControlEventTouchUpInside];
    }

    //set button label
    [button setTitle:[socialArray objectAtIndex:0] forState:UIControlStateNormal];

    return button;
}

What I really want to do is set the image of the button based on the specified image in an array. So, the first button gets the PNG file specified at index 0, second button gets image at index 1 and so on.

Any advice on how I can do that?


Solution

  • UIImage *image = [socialArray objectAtIndex:index];
    

    (You have to do this outside of the if statement, otherwise the image wouldn't be set for buttons that are reused.)