简体   繁体   English

如何在所有视图控制器上设置一个标签来设置分数?

[英]How to make one label to set score on all view controllers?

I have a label and I need it to show the score, coins ect on every ViewController, That means when The score changes it changes every where throughout the whole app... 我有一个标签,我需要它来显示每个ViewController上的分数,硬币等,这意味着当分数改变时,它会改变整个应用程序中的每个位置......

I've tried to set a label to show score on the whole app but I cant figure out how! 我试图设置一个标签来显示整个应用程序的分数,但我无法弄清楚如何!

Please help 请帮忙

This is what I have so Far In the View Controller: 这就是我在视图控制器中所拥有的:

 -(void)viewDidLoad
{
{
[super viewDidLoad];


    NSError *error;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //1
    NSString *documentsDirectory = [paths objectAtIndex:0]; //2
    path = [documentsDirectory stringByAppendingPathComponent:@"SettingsList.plist"]; //3

    NSFileManager *fileManager = [NSFileManager defaultManager];

    if (![fileManager fileExistsAtPath: path]) //4
    {
        NSString *bundle = [[NSBundle mainBundle] pathForResource:@"SettingsList"ofType:@"plist"]; //5 //5

        [fileManager copyItemAtPath:bundle toPath: path error:&error]; //6
    }

    savedStock = [[NSMutableDictionary alloc] initWithContentsOfFile: path];

    nPoint = [[savedStock objectForKey:@"point"] intValue];
    [giftAmount setText:[NSString stringWithFormat:@"%d",nPoint]];

[self updateCurrencyBalance];
[self zoneLoading];
}

//adcolony
- (void) viewDidAppear:(BOOL)animated
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateCurrencyBalance) name:kCurrencyBalanceChange object:nil];

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(zoneReady) name:kZoneReady object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(zoneOff) name:kZoneOff object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(zoneLoading) name:kZoneLoading object:nil];
}

// Get currency balance from persistent storage and display it
- (void)updateCurrencyBalance {
NSNumber* wrappedBalance = [[NSUserDefaults standardUserDefaults] objectForKey:kCurrencyBalance];
NSUInteger balance = wrappedBalance && [wrappedBalance isKindOfClass:[NSNumber class]] ? [wrappedBalance unsignedIntValue] : 0;
[giftAmount setText:[NSString stringWithFormat:@"%u", balance]];

[savedStock setObject:[NSNumber numberWithFloat:nPoint = balance] forKey:@"point"];
[savedStock writeToFile: path atomically:YES];

}

I have an action in the other PlayViewController which (minusus) -200 coins, but its not updating in the ViewController? 我在其他PlayViewController中有一个动作(减去)-200硬币,但它在ViewController中没有更新?

One way is to use NSNotificationCenter. 一种方法是使用NSNotificationCenter。

Add this code to all the places that change the value of your score: 将此代码添加到更改分数值的所有位置:

- (void)updateScore:(NSNumber *)newValue
    // update the score
    self.score = newValue;

    // create an dictionary object containing the score to be sent with the notification
    NSMutableDictionary* userInfo = [NSMutableDictionary dictionary];
    [userInfo setObject:self.score forKey:@"score"];

    // Add this to send a notification to all the listeners in the whole app
    [[NSNotificationCenter defaultCenter] postNotificationName:@"NotificationScoreChanged" object:nil userInfo:userInfo];
}

In the viewDidLoad methods of your view controllers, add this code: 在视图控制器的viewDidLoad方法中,添加以下代码:

- (void)viewDidLoad:(BOOL)animated
{
    [super viewDidLoad:animated];

    // Add this code to start receiving notifications (become a listener)
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(scoreChanged:) name:@"NotificationScoreChanged" object:nil];
}

Then somewhere in your view controllers, add this method to update your UI: 然后在视图控制器的某个位置添加此方法以更新UI:

- (void)scoreChanged:(NSNotification *)notification
{
   // retrieve the score results
    if ([notification.name isEqualToString:@"NotificationScoreChanged"])
    {
        NSDictionary *userInfo = notification.userInfo;
        NSNumber *score = [userInfo objectForKey:@"score"];

        // and update your labels
        self.scoreLabel.text = [score description];
    }

And in your view controllers, add dealloc: 在视图控制器中,添加dealloc:

- (void)dealloc
{
    //Unregister yourself (stop listening)
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

Note: you should adapt the code depending on how you store and retrieve your score. 注意:您应该根据存储和检索分数的方式调整代码。 Ie, if you use NSUserDefaults (see @erid's answer), CoreDate, etc. 即,如果您使用NSUserDefaults(请参阅@ erid的答案),CoreDate等。

Use NSUserDefaults for storing data (Data gets deleted only when program is removed from iOS Device or you can remove it manually). 使用NSUserDefaults存储数据(仅当从iOS设备中删除程序时才会删除数据,或者您可以手动将其删除)。

Storing Value on NSUserDefaults 在NSUserDefaults上存储值

//text is your label.text, and each time you change it, save it to user details
NSString *text;

//Store them to NSUserDefaults with a specific key
[[NSUserDefaults standardUserDefaults] setObject:text forKey:@"label"];

Getting value back 重拾价值

NSString *textValue = [[NSUserDefaults standardUserDefaults] objectForKey:@"label" ];
label.text = textValue;

You can try adding NSNotification to your program to notificate you when the NSString you set to change the label changes, and there you can set this value to NSUserDefaults . 您可以尝试将NSNotification添加到程序中,以便在设置为更改标签的NSString更改时对您进行通知,并且可以将此值设置为NSUserDefaults

As David said this is not the best way to do this, but you have to read more about Singletons if you need to save your DATA until the app is closed. 正如大卫所说,这不是最好的方法,但是如果您需要保存数据直到应用程序关闭,您必须阅读更多关于单身人士的信息

Hope it helps 希望能帮助到你

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM