簡體   English   中英

如何在Objective-C中使用for循環顯示存儲在數組中的值

[英]how to display the value stored in array by using for loop in objective-c

邏輯:

  • 陣列中有5張圖片

例:

apple.png,mango.png,bird.png,sun.png,moon.png

我需要在該數組中使用arc4random ,所以索引為1,所以值得到了mango.png

在我存儲的其他數組中

number = [[NSMutableArray alloc]initWithObjects:@"4",@"2",@"9",@"1",@"8",@"7",@"5",@"3",@"6",@"10", nil];

並使用arc4random ,我得到的輸出為index:2 value as:9

那么我需要在圖像視圖中打印9次芒果圖像。

請幫助如何使用Objective-C進行編碼

根據我的理解,您必須根據隨機數在ImageView顯示隨機Image。

看下面的代碼,

images = [[NSMutableArray alloc]initWithObjects:[UIImage imageNamed:@"Navarre-Family-Eye-Care-Navarre-Florida-Optometrist-Santa-Christmas-Toy-Safety.jpg"],[UIImage imageNamed:@"Christmas-Wallpapers-HD-Picture.jpg"],[UIImage imageNamed:@"Christmas-Wallpaper-jesus-9413550-1024-768.jpg"],[UIImage imageNamed:@"tree.jpg"],[UIImage imageNamed:@"luxury-christmas-napkins-father-christmas-1635-p.jpg"],[UIImage imageNamed:@"Navarre-Family-Eye-Care-Navarre-Florida-Optometrist-Santa-Christmas-Toy-Safety.jpg"],[UIImage imageNamed:@"Christmas-Wallpapers-HD-Picture.jpg"],[UIImage imageNamed:@"Christmas-Wallpaper-jesus-9413550-1024-768.jpg"],[UIImage imageNamed:@"tree.jpg"],[UIImage imageNamed:@"luxury-christmas-napkins-father-christmas-1635-p.jpg"], nil];

int randomIndex=arc4random() % images.count;
UIImage *selectedImage = [images objectAtIndex:randomIndex]; //random selected image

number = [[NSMutableArray alloc]initWithObjects:@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"10", nil];
int randomNumber = arc4random() % number.count; //random selected number

NSInteger indexValue = [number indexOfObject:[NSString stringWithFormat:@"%d",randomNumber]]; // get index number of your random number

for (int i = 0; i <indexValue ; i++) {
    NSLog(@"%@", selectedImage);
    yourImageView.Image = selectedImage;
}

重要的是您要在哪里顯示圖像。

從上面的代碼片段中,我可以理解,v(NSArray)是分配了UIImage的。 如果要將v用作NSArray,然后將UIImage作為對象添加到Array,則可以使用索引訪問圖像。

NSArray *v=[[NSArray alloc] initWithObjects:[imagesArray objectAtIndex:randomIndex], nil];

然后您可以使用以下代碼NSLog image對象

for (int i= 0 ; i<ran; i++) {
    NSLog(@"%@",[v objectAtIndex:0]);
   _cardsImageView.image = [v objectAtIndex:0]
}

您必須根據隨機數在NSLog中顯示圖像的次數。 因此,只需在現有代碼的末尾添加以下代碼即可。

int count = [[number objectAtIndex:ran] intValue];
    for(int i=0; i<count; i++)
    {
        NSLog(@"%@",v);
    }

暫無
暫無

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

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