gpt4 book ai didi

iphone - 每次应用启动时仅调用一次方法

转载 作者:行者123 更新时间:2023-12-01 19:06:55 26 4
gpt4 key购买 nike

嘿,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 中)的颜色。问题是每次我回到 View 我都会得到不同的颜色。

但是,我想设置 UIView 的随机颜色仅在应用程序启动后。这个颜色应该 入住 直到申请为 关闭来自多任务处理。我看不出有什么办法可以解决这个问题。我尝试调用 applicationDidFinishedLaunchingWithOptions 中的代码方法,但我没有成功。

我也试过 dispatch_once方法只调用一次,但您可能会想到颜色从未再次调用,因此第二次加载 View 时没有颜色。

如果你能帮助我,我真的很感激。

提前致谢,

诺亚

编辑:

我的标题:
@interface ViewController : UIViewController {

IBOutlet UIView *colorTransparentView;
}


@end

最佳答案

使用静态变量怎么样?用 0 初始化它,在你的 View 中改变颜色后会出现。将其设置为 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;
}

关于iphone - 每次应用启动时仅调用一次方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19126223/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com