开发者

Change UIbutton Image on click

I have stored 5 images in an mutable array and displayed them randomly on iPhone view by appending them in UIButton . now I want to change the image o开发者_如何学运维n a button on which I will click. but in my code only the last image changes not the image on which I called the action.


Here is the code for 3 buttons which highlights the clicked button

-(void) changeButtonImage:(id) sender{
    [button1 setBackgroundImage:[UIImage imageNamed:@"button1Image_off.png"] forState:UIControlStateNormal];
    [button2 setBackgroundImage:[UIImage imageNamed:@"button2Image_off.png"] forState:UIControlStateNormal];
    [button3 setBackgroundImage:[UIImage imageNamed:@"button3Image_off.png"] forState:UIControlStateNormal];

    UIButton *button = sender;

    if (button.tag == 0) {
        [button1 setBackgroundImage:[UIImage imageNamed:@"button1Image_on.png"] forState:UIControlStateNormal];
    }else if (button.tag == 1) {
        [button2 setBackgroundImage:[UIImage imageNamed:@"button2Image_on.png"] forState:UIControlStateNormal];
    }else if (button.tag == 2) {
        [button3 setBackgroundImage:[UIImage imageNamed:@"button3Image_on.png"] forState:UIControlStateNormal];
    }

}

hope this helps...

hAPPY cODING...


If you are looking for how to change the image on a button just do:

[myButton setImage:[UIImage imageNamed:@"myImage.png"] forState:UIControlStateNormal];

You can have it loop through your array but creating a variable to store what image index you are on. Then just go to the next one using the statement above to assign the image.


Do you have an Outlet (IBOutlet) for each of the buttons. You should list each one as an outlet, and just use Interface Builder to connect each button to those variables. Then create a function for the touchUpInside event of each button. Make this buttonPressed. make this function something like:

-(void) buttonPressed:(id) sender
{
     ((UIButton *)sender).image = [UIImage imageNamed:@"Image.png"];
}

You will want to set a variable like currentImage to track what image is set. Each time you click increase that variable (currentImage++). If it gets > some final amount set it back to 0. Then you can just do

if (currentImage == 0) { set first image; } else if (currentImage == 1) { set second image.. }

etc...

Does this help?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜