使用UIButton更新UIImageView中的图像

问题描述:

我对应用程序开发并不陌生,我正在构建一个应用程序(这将会更加复杂,但这只是我稍后扩展的基础)。我目前所看到的是UIImageViewUIButton,代码如下。我可以通过按钮来从资源文件夹中设置图像,但是我想要的是,每次按下时,按钮都会用新图像更新UIImageView。按一次= image1,按两次= image2 ...等从我一直在阅读我认为我应该有一个数组中的图像与一个键或什么,然后我可以用++更新它我知道这是非常模糊,但正如我所说我真的很新,所以任何帮助将不胜感激!使用UIButton更新UIImageView中的图像

@interface NextImageViewController : UIViewController { 

    IBOutlet UIImageView *imageView;  
} 

- (IBAction) nextImagePush; 

@end 

@implementation 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; 
} 

尝试类似的东西。您必须设置初始图像并根据设置的内容更改计数。

+0

Mike007非常感谢你的工作!这个网站真棒! –

一个非常基本的方法是设置一个整数。将其定义为0, ,并在您第一次单击按钮时将其添加1。

这绝对不是工作代码,但它只是为了帮助你获得开始。我强烈建议在iOS或Beginning IPhone 4 Development这本书上写下Big Nerd Ranch的书。

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

btw我推荐使用Saphrosit的方法。 – Sum

您可以简单地创建一个NSArrayNSMutableArray并与所有你想要显示的图像填充它。然后,使用一个变量可见在全局范围内(即你的界面的字段),可以使用

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

这段代码也将显示第一图像显示在最后一个之后。