簡體   English   中英

圖像陣列IBAction以查看陣列中的下一個圖像

[英]Image Array IBAction to view next image in the array

感謝@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以在單擊后成功遍歷數組中的圖像?

創建一個圖像數組,將其命名為圖像,初始化一個整數“ 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];
}
}

您需要刪除

currentImage = 0;

這意味着將始終加載第一個圖像

您需要添加檢查以查看currentImage是否大於imagearray:

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

您的遞增邏輯已損壞,因此第一次單擊將無濟於事,並且您永遠都無法到達最后一張圖片。 如果將3.png添加到數組中,這將更加明顯。 逐步閱讀代碼,觀察每一步代碼的執行情況可能會很有幫助。

正確的遞增邏輯如下所示:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM