【问题标题】:Image Array IBAction to view next image in the arrayImage Array IBAction 查看数组中的下一个图像
【发布时间】:2011-03-26 22:54:27
【问题描述】:

感谢@JFoulkes,我的应用程序可以在单击下一步按钮时显示数组中的第一个图像。但是,当我再次单击它时,它不会显示数组中的下一个图像。这让我相信我的下一个按钮的 IBAction 不太正确。

这是我到目前为止的代码......

在我的 .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];
}

这是我的 IBAction,它只显示数组中的第一个图像 (1.png),再次单击时不会将 UIImageView 更改为第二个数组图像 (2.png):

-(IBAction)next {

 if (currentImage + 1 == [imageArray count])
        currentImage = 0;
    UIImage *img = [imageArray objectAtIndex:currentImage];
    [imageView setImage:img]; 
   currentImage++;
}

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

【问题讨论】:

    标签: iphone objective-c xcode ios4


    【解决方案1】:

    您的递增逻辑已损坏,因此第一次点击将无济于事,您永远无法到达最后一张图片。如果您将 3.png 添加到您的数组中,这将更加明显。单步调试代码,观察它在每一步的作用可能会很有启发性。

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

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

    【讨论】:

    • Anomie - 你将如何使用这个递增逻辑来编码之前的动作?
    • @Ian:currentImage--当然可以,然后把测试改成if (currentImage < 0) currentImage = imageArray.count - 1;
    • 啊,我明白了。最后,最好设置我想在 InterfaceBuilder 中加载视图时看到的初始图像,还是将其设置在我在 viewDidLoad 中的数组中?如果是后者,我是否将其定义为 currentImage = 0;?
    • 我建议从 viewDidLoad 中的数组中设置它,这样如果您更改图像的顺序,您将不会忘记在其他地方进行更正。
    【解决方案2】:

    你需要删除

    currentImage = 0;
    

    这意味着总是会加载第一张图片

    你需要添加一个检查来查看currentImage是否大于imagearray:

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

    【讨论】:

    • 经过5个小时的尝试,你帮我搞定了!我使用 currentImage=0 是因为我认为它是 if 语句的一部分,并且会循环回到数组末尾的第一个图像。
    • 这行不通。我假设视图开始在索引 0 处显示图像。在第一次调用之后,它将仍然在索引 0 处显示图像。只有在第二次调用之后,它似乎才能正常工作。如果结合prev 的类似实现,您可能会发现更改方向会给您带来更多问题。
    • 几乎,它会让你走到最后并抛出一个 NSRangeException。将 &lt;= 更改为 &lt; 即可。
    【解决方案3】:

    创建一个图像数组,将其命名为图像,初始化一个整数“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];
    }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-06
      • 2020-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多