[英]Call method only once every app launch
嘿家伙在Stackoverflow!
我需要你的幫助。 我正在尋找一種方法, 只在應用程序啟動后調用我的方法一次並“保存”UIView的顏色狀態。 首先,我將向您展示我的代碼,我可以更好地解釋它:
- (void)viewWillAppear:(BOOL)animated {
NSArray *colors = [NSArray arrayWithObjects:[UIColor myWhiteColor],[UIColor myBlueColor],[UIColor myCyanColor],[UIColor myGreenColor],[UIColor myOrangeColor],[UIColor myPurpleColor],[UIColor myRedColor],[UIColor myViolettColor],[UIColor myYellowColor], nil]; NSInteger randomIndex = random() % [colors count]; colorTransparentView.backgroundColor = [colors objectAtIndex:randomIndex]; colorTransparentView.opaque = NO; colorTransparentView.alpha = 1.0;
}
現在我向你解釋我的問題。 如您所見,每次調用“viewWillAppear”方法時,上面的代碼都會更改UIView的顏色。 代碼隨機地將與IBOulet鏈接的UIView(在.xib中)的顏色更改為頭文件。 問題是,每次回到視圖時,我都會得到不同的顏色。
但是,我只想在應用程序啟動后設置UIView
的隨機顏色。 此顏色應保持不變,直到應用程序從多任務關閉 。 我看不出任何解決方法。 我試圖在applicationDidFinishedLaunchingWithOptions
方法中調用代碼,但我並不熟練。
另外我嘗試使用dispatch_once
方法只調用一次,但是你可能會想到顏色再也沒有被調用過,所以第二次加載時視圖沒有顏色。
如果你能幫助我,我真的會感激不盡。
提前致謝,
諾亞
編輯:
我的標題:
@interface ViewController : UIViewController {
IBOutlet UIView *colorTransparentView;
}
@end
那么使用靜態變量呢? 用0初始化它,並在您的視圖中更改顏色后將出現。 將其設置為1並繼續檢查它。
int static colortaken = 0;
int static colorindex;
- (void)viewWillAppear:(BOOL)animated
{
NSArray *colors = [NSArray arrayWithObjects:[UIColor myWhiteColor],[UIColor myBlueColor],[UIColor myCyanColor],[UIColor myGreenColor],[UIColor myOrangeColor],[UIColor myPurpleColor],[UIColor myRedColor],[UIColor myViolettColor],[UIColor myYellowColor], nil];
if (colortaken == 0)
{
NSInteger randomIndex = random() % [colors count];
colorindex = randomIndex;
colorTransparentView.backgroundColor = [colors objectAtIndex:randomIndex];
colorTransparentView.opaque = NO;
colorTransparentView.alpha = 1.0;
}
else
{
// do nothin
colorTransparentView.backgroundColor = [colors objectAtIndex:colorindex];
colorTransparentView.opaque = NO;
colorTransparentView.alpha = 1.0;
}
// at end
colortaken = 1;
}
使用dispatch_once。 您可以閱讀一般的單例方法,但這是推薦的方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.