gpt4 book ai didi

ios - xcode - 当我更改 View 时标签更改值

转载 作者:行者123 更新时间:2023-11-29 02:53:22 25 4
gpt4 key购买 nike

我四处寻找,没有找到任何东西,将不胜感激。我是 Objective-C 和 Xcode 的新手。

在我的应用程序中,玩家从 100 个硬币开始,这在标签中表示。当用户单击一个按钮花费 10 个硬币时,会出现一个弹出框并询问“你确定吗”,用户可以单击确定或取消。

如果用户点击“确定”,他们将花费 10 个硬币。目前,在模拟器中,当我在同一个 View 中时,一切都很好,100 下降到 90 等等......但是当我转到另一个 View 然后再次返回时,硬币数量又回到 100。这与用户退出应用程序时相同。

这是我的代码:

.h文件

//Coin
IBOutlet UILabel * coinCount;

.m文件

int coinAmount = 100;

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex == 0)
{
NSLog(@"user pressed Cancel");
// Any action can be performed here
}
else
{
NSLog(@"user pressed OK");

coinAmount -= 10;
[coinCount setText:[NSString stringWithFormat:@"%d", coinAmount]];
NSString * string = [NSString stringWithFormat:@"%d", coinAmount];

//Save coin amount
NSString * saveCoinAmount = string;
NSUserDefaults * defaultsCoinAmount = [NSUserDefaults standardUserDefaults];
[defaultsCoinAmount setObject:saveCoinAmount forKey:@"saveCoinLabel"];
[defaultsCoinAmount synchronize];
}

这似乎保存了新的硬币数量,所以现在当用户转到另一个 View 并返回时,我尝试加载保存的硬币数量:

   - (void)viewDidLoad
{
[super viewDidLoad];
//Coin Label
NSUserDefaults * defaultsLoadCoin = [NSUserDefaults standardUserDefaults];
NSString * loadCoinLabel = [defaultsLoadCoin objectForKey:@"saveCoinLabel"];
[coinCount setText:loadCoinLabel];

}

如有任何帮助,我们将不胜感激!

最佳答案

您的问题是您将硬币存储在两个地方 - 整数变量和标签。当您返回 View 时,您可以将保存的硬币数量直接恢复到标签中,但是当您执行“购买”时,您使用的是整数,该整数已被重新初始化为 100。

我还建议您改掉使用实例变量并使用属性的习惯。

你应该做这样的事情 -

.m 文件

@interface MyClass ()             // Change this to suit your class name

@property NSInteger coinAmount;
@property (weak,nonatomic) IBOutlet UILabel *coinLabel;

@end


@implementation MyClass

- (void)viewDidLoad
{
[super viewDidLoad];
//Coin Label
NSUserDefaults * defaultsLoadCoin = [NSUserDefaults standardUserDefaults];
if ([defaultsLoadCoin objectForKey:@"coins] == nil) {
self.coinAmount=100;
[defaultsLoadCoin setInteger:self.coinAmount forKey:@"coins"];
}
else {
self.coinAmount = [defaultsLoadCoin integerForKey:@"coins"];
}

self.coinLabel.text=[NSString stringWithFormat:@"%ld",self.coinAmount];

}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex == 0)
{
NSLog(@"user pressed Cancel");
// Any action can be performed here
}
else
{
NSLog(@"user pressed OK");

self.coinAmount -= 10;
self.coinLabel.text=[NSString stringWithFormat:@"%ld",self.coinAmount];

//Save coin amount
NSString * saveCoinAmount = string;
NSUserDefaults * defaultsCoinAmount = [NSUserDefaults standardUserDefaults];
[defaultsCoinAmount setInteger:self.coinAmount forKey:@"coins"];;
[defaultsCoinAmount synchronize];
}

关于ios - xcode - 当我更改 View 时标签更改值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24218180/

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