2012-07-06 78 views
2

我有iPhone的初学者。我有一个阵列中的图像,但它返回NULL单击下一个按钮时如何逐个显示图像?

我有使用此代码

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
images= [[NSArray arrayWithObjects: 
         [UIImage imageNamed:@"1.png"], 
         [UIImage imageNamed:@"2.png"], 
         [UIImage imageNamed:@"3.png"], 
         [UIImage imageNamed:@"4.png"], 
         nil] retain]; 
} 
-(IBAction)Next 
{ 


    currentImage++; 
    if(currentImage>=[images count]) 
    { 
     currentImage=0; 


    } 

    UIImage *img=[images objectAtIndex:currentImage]; 
    [animalphoto setImage:img]; 
    NSLog(@"print:%@",currentImage); 

} 

第一次点击按钮图像显示,但第二次不显示图像和返回NULL值..给出任何建议,并源代码适用于我们的代码。

回答

0

加入验证代码在你viewDidLoad方法来检查图像被正确加载:

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    images= [[NSArray arrayWithObjects: 
         [UIImage imageNamed:@"1.png"], 
         [UIImage imageNamed:@"2.png"], 
         [UIImage imageNamed:@"3.png"], 
         [UIImage imageNamed:@"4.png"], 
         nil] retain]; 
    NSAssert([images count] == 4, @"Failed to load one or more images"); 
} 

IBAction方法应该有一个sender参数虽然,不应该吗?

-(IBAction)Next:(id)sender 
{ 
    currentImage = (currentImage + 1) % [images count]; 
    NSLog(@"currentImage=%d",currentImage); 
    UIImage *img=[images objectAtIndex:currentImage]; 
    [animalphoto setImage:img]; 
} 

您的代码对我来说看起来不错(但我是Mac开发人员),所以我怀疑这是一个包装问题。

0

使用此方法和currentImage = 0:

-(IBAction)Next 
{ 

    if(currentImage>=[images count]) 
    { 
    currentImage=0; 
    } 

UIImage *img=[images objectAtIndex:currentImage]; 
[animalphoto setImage:img]; 
NSLog(@"print:%@",currentImage); 
currentImage++; 

} 
+0

这将导致异常;测试应该是:if(currentImage> = [images count])。 – trojanfoe 2012-07-06 11:07:51

+0

trojanfoe你正确 – 2012-07-06 11:15:52

0

你的代码是完全正确的,你已经写了,除非你打印currentImage因为currentImage为整型,但你提到的NSLog“%@”字符串类型是什么。这就是为什么它显示错误。您只需将其更改为

NSLog(@"print:%d",currentImage); 

我认为这会对您有所帮助。

相关问题