很好的计数器可以在iPhone视图中转到阵列中的下一个和上一个图片



在一个视图中,该视图将显示图像(在一个数组中),并具有连接到各自的next和previor方法的下一个和上一个按钮。

如何创建用于objectAtIndex:counter的计数器?

阵列中图片导航的要求是:

  • 单击下一张->下一张图片
  • 单击上一张->上一张图片
  • 点击下一张,它是最后一张图片->转到第一张图片
  • 单击上一张和它的第一张图片->转到最后一张图片
  • 没有图片(第一次运行和创建之前)->什么都不做

您可以轻松完成您需要为该类创建一个全局变量(count),然后执行此操作

-(IBAction)previousImage:(id)sender
{
    if(count==0)
    {
        count=array.count-1;
        imageView.image = [UIImage imageNamed:[array objectAtIndex:count]];
    }
    else
    {
        count--;
        imageView.image = [UIImage imageNamed:[array objectAtIndex:count]];
    }
}
-(IBAction)nextImage:(id)sender
{
    if(count==array.count-1)
   {
        count=0;
        imageView.image = [UIImage imageNamed:[array objectAtIndex:count]];
  } 
    else
    {
        count++;
        imageView.image = [UIImage imageNamed:[array objectAtIndex:count]];
    }
}

这里的total是图像的数量。

-(IBAction)previous:(id)sender{
    if(count==0)
        count=total-1;
    else
        count--;
}
-(IBAction)next:(id)sender{
    if(count==total-1)
        count=0;
    else
        count++;
}

基于上面的答案和注释实现的代码(我使用一个singleton和coreData来保存图像):

static NSUInteger count;
- (IBAction)onNext{

DataControllerSingleton *singletonData= [DataControllerSingleton singleDataController];
NSInteger total = [singletonData countOfList];
self.cares = [singletonData allObjects];
if(count == total-1)
{
    count=0;
    NSObject *ob = [cares objectAtIndex:count];
    self.backgroundImage.image = [[UIImage alloc]initWithData:[ob          
    valueForKey:@"imageData"]];
}
else
{
    count++;
    NSObject *ob = [cares objectAtIndex:count];
    self.backgroundImage.image = [[UIImage alloc]initWithData:[ob 
    valueForKey:@"imageData"]];
}
}


 - (IBAction)onPrevious{
DataControllerSingleton *singletonData= [DataControllerSingleton singleDataController];
NSInteger total = [singletonData countOfList];
self.cares = [singletonData allObjects];
if(count==0)
{
    count=total-1;
    NSObject *ob = [cares objectAtIndex:count];
    self.backgroundImage.image = [[UIImage alloc]initWithData:[ob    
    valueForKey:@"imageData"]];
}
else
{
    count--;
    NSObject *ob = [cares objectAtIndex:count];
    self.backgroundImage.image = [[UIImage alloc]initWithData:[ob     
   valueForKey:@"imageData"]];
}
}

最新更新