簡體   English   中英

有沒有一種方法可以將相同的圖像設置為多個UIimageViews?

[英]Is there a way to set the same image to many UIimageViews?

我正在使用圖像處理量很大的iOS應用程序,發現自己一次又一次地鍵入幾乎同一行:

...
A016.image = [UIImage imageNamed:img21];
A017.image = [UIImage imageNamed:img21];
A018.image = [UIImage imageNamed:img21];
...

現在,我問您:有沒有一種方法可以將UIImageViews名稱存儲在Array之類的東西中? 只是為了美化我非常丑陋的代碼。 /約翰

是的,您可以將UIImageViews放在一個數組中,並將其放在for中。

UIImageView * imageView1;
UIImageView * imageView2;
UIImageView * imageView3;
NSArray * imageViewsArray = [NSArray arrayWithObjects:imageView1,imageView2,imageView3,nil];

for (UIImageView * currentImageView in imageViewsArray) {

     currentImageView.image = [UIImage imageNamed:img21];

}

當然,您可以簡化這樣的事情。 但是,尚不清楚上下文到底是什么。

如果將所有圖像視圖都放在一個數組中,則可以執行以下操作。

// Assume an NSArray called imageViews exists with all the UIImageView instances in it.
for (UIImageView *imageView in imageViews) {
    imageView.image = [UIImage imageNamed:img21];
}

如果您的圖像視圖還不在數組中,實際上被稱為A016,A017等,那么我建議您更改代碼設計。 這樣的事情絕不是一個好主意。 這將導致不良的代碼,難以維護。 如果這是某種圖像表,請首先嘗試將圖像視圖放入數組中。

話雖這么說,有多種方法可以將類似的變量放入數組中。 如果將它們聲明為@properties或ivars,則可以執行以下操作。

NSMutableArray *imageViews = [NSMutableArray arrayWithCapacity:20];
for (int i = 0; i < 20; i++) {
    NSString *variableName = [NSString stringWithFormat:@"A0%d", i];
    UIImageView *imageView = [self valueForKey:variableName];
    [imageViews addObject:imageView];
}

之后,您可以將數組另存為ivar並執行與上述相同的操作。

更加硬編碼的版本將是自己將圖像視圖簡單地放入數組中:

NSArray *imageViews = [NSArray arrayWithObjects:..., A016, A017, A018,..., nil];

但是我真的建議不要使用這樣的索引變量名稱。

暫無
暫無

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

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