Iphone Image Array iAction可查看阵列中的下一幅图像

Iphone Image Array iAction可查看阵列中的下一幅图像,iphone,objective-c,xcode,ios4,Iphone,Objective C,Xcode,Ios4,多亏了@JFoulkes,我的应用程序在单击“下一步”按钮时显示了阵列中的第一幅图像。但是,当我再次单击它时,它不会显示阵列中的下一个图像。这让我相信我对“下一步”按钮的选择不太正确 这是我到目前为止的代码 在我的.h文件中,我声明: IBOutlet UIImageView *imageView; NSArray *imageArray; NSInteger currentImage; 我还补充说: -(IBAction) next; 在.m文件中,我有: -(void) viewDidL

多亏了@JFoulkes,我的应用程序在单击“下一步”按钮时显示了阵列中的第一幅图像。但是,当我再次单击它时,它不会显示阵列中的下一个图像。这让我相信我对“下一步”按钮的选择不太正确

这是我到目前为止的代码

在我的.h文件中,我声明:

IBOutlet UIImageView *imageView;
NSArray *imageArray;
NSInteger currentImage;
我还补充说:

-(IBAction) next;
在.m文件中,我有:

-(void) viewDidLoad;
{
imageArray = [[NSArray arrayWithObjects: 
                [UIImage imageNamed:@"1.png"], 
                  [UIImage imageNamed:@"2.png"], 
                  nil] retain];
}
这是我的iAction,它只显示数组中的第一个图像(1.png),再次单击时不会将UIImageView更改为第二个数组图像(2.png):

根据代码,如何更改iAction以在单击后成功遍历数组中的图像?

您需要删除

currentImage = 0;
这意味着将始终加载第一个图像

您需要添加检查以查看currentImage是否大于imagearray:

if (currentImage +1 < [imageArray count])
{
    currentImage++;
    UIImage *img = [imageArray objectAtIndex:currentImage];
    [imageView setImage:img]; 
}
if(currentImage+1<[imageArray count])
{
currentImage++;
UIImage*img=[imageArray objectAtIndex:currentImage];
[图像视图设置图像:img];
}

您的递增逻辑已中断,因此第一次单击将不起任何作用,您永远无法到达最后一张图像。如果将3.png添加到数组中,这会更明显一些。一步一步地浏览代码,观察它在每一步都做了些什么,这可能会很有启发性

正确的递增逻辑如下所示:

- (void)next {
    currentImage++;
    if (currentImage >= imageArray.count) currentImage = 0;
    UIImage *img = [imageArray objectAtIndex:currentImage];
    [imageView setImage:img];
}

创建一个图像数组,将其命名为图像,初始化一个整数“i”。
在视图中,创建一个imageView和两个按钮(下一个和上一个),
将此代码用于按钮操作

-(void)nextButton:(id)sender
{
if (i < (array.count-1))
{
    i=i+1;
     imageView.image = [images objectAtIndex:i];
}
}

-(void)previousButton:(id)sender
{
if(i >= 1)
{
    i=i-1;
    imageView.image=[images objectAtIndex:i];
}
}
-(void)下一个按钮:(id)发送者
{
如果(i<(数组计数-1))
{
i=i+1;
imageView.image=[images objectAtIndex:i];
}
}
-(作废)上一个按钮:(id)发送者
{
如果(i>=1)
{
i=i-1;
image=[images objectAtIndex:i];
}
}

经过5个小时的尝试,你帮我找到了答案!我使用currentImage=0是因为我认为它是if语句的一部分,并且会循环回数组末尾的第一个映像。这不会很好地工作。我假设视图开始显示索引为0的图像。在第一次调用之后,它仍将在索引0处显示图像。只有在第二次呼叫之后,它才能正常工作。如果与类似的
prev
实现结合使用,您可能会发现改变方向会给您带来更多问题。几乎,它会让您走到最后一步并抛出一个异常。更改
失范-如何使用此递增逻辑对上一个操作进行编码?@Ian:
currentImage--
,当然,然后将测试更改为
if(currentImage<0)currentImage=imageArray.count-1啊,我明白了。最后,在InterfaceBuilder中加载视图时设置我想要查看的初始图像,还是在viewDidLoad中的数组中设置它更好?如果是后者,我是否将其定义为currentImage=0;?我建议从viewDidLoad中的数组中进行设置,因为这样,如果更改图像的顺序,您就不会忘记在其他位置进行更正。
-(void)nextButton:(id)sender
{
if (i < (array.count-1))
{
    i=i+1;
     imageView.image = [images objectAtIndex:i];
}
}

-(void)previousButton:(id)sender
{
if(i >= 1)
{
    i=i-1;
    imageView.image=[images objectAtIndex:i];
}
}