开发者

Using a UIButton to update the image in a UIImageView

I'm really new to app development and I am building an app (that will be more complex but this is just the basis of it which I will later expand). What I have currently is view with a UIImageView and UIButton, code below. I can get the button to set an image from the resources folder, but what I want is for the button to update the UIImageView with a new image each time it is press e.g. press once = image1, pressed twice = image2...etc From what I have been reading I think I should have the images in an array with a key or something then I can just update it with ++ I know this is really vague but as I said I'm really new so any help would be greatly appreciated!

@interface NextImageViewController : UIViewController {

    IBOutlet UIImageView *imageView;    
}

- (IBAction) nextImagePush;

@end

@i开发者_开发问答mplementation NextImageViewController

- (IBAction) nextImagePush {

    UIImage *img = [UIImage imageNamed:@"image1"];
    [imageView setImage:img];    
}


@interface NextImageViewController : UIViewController {

    IBOutlet UIImageView *imageView;
    NSInteger imageCount;
    NSArray * imageArray;   
}

- (IBAction) nextImagePush;

@end

@implementation NextImageViewController

- (IBAction) nextImagePush {


    UIImage *img = [UIImage imageNamed:[imageArray objectAtIndex:imageCount]];
    [imageView setImage:img];    
    imageCount++;
    if (imageCount >= [imageArray count]){
        imageCount = 0;
    }

}

- (void) viewDidLoad {
    imageArray = [[NSArray alloc] 
        initWithObjects:@"image1", @"image2", @"image3", nil];
    imageCount = 0;
}

Try something like that. You wil have to set the initial image and change the count depending on what you set it.


You can simply create a NSArray or NSMutableArray and fill it with all the images you want to show. Then, using a variable visible at global scope (ie a field of your interface), you can use

[imageView setImage:[arrayOfImages objectAtIndex:(index++ % [arrayOfImages count])]];

This code will also show the first image after the last one is displayed.


A really rudimentary way to do this is set a integer. Define it as 0, and the first time you click the button you add 1 to it.

This definitely isn't working code, but its just to help you get a start. I strongly suggest a book like Big Nerd Ranch's book on iOS or Beginning IPhone 4 Development.

-(IBAction)pic
if variable == 0 {
//show the first image
variable++; 
 }
else if variable == 1 {
//show the second image
variable++; 
 }
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜