Changing the Value of NSTextField doesn't update label?

感情迁移 提交于 2020-01-06 07:32:47

问题


I'm trying to change a label from the AppDelegate. I can change the label with an IBAction that runs a changeLabel in the implementation of the class that has the label, but if I try to run changeLabel from the AppDelegate it changes the value (I have an NSLog), but doesn't update label.

Here's the code:

#import <Foundation/Foundation.h>

@interface testLabelThingy : NSObject
@property (strong) IBOutlet NSTextField *daLabel;
- (id) init;
- (void)changeLabel;
- (IBAction)daButton:(id)sender;
@end

and:

#import "testLabelThingy.h"

@implementation testLabelThingy
@synthesize daLabel;
- (id) init{
    self.daLabel = [[NSTextField alloc] init];
    return self;
}
- (IBAction)daButton:(id)sender{
    [self changeLabel];
}
- (void)changeLabel{
    NSLog(@"Change Label Function. Current value is: %@", [self.daLabel stringValue]);
    if([[self.daLabel stringValue] isEqualToString:@"Bloog"]){
        [self.daLabel setStringValue:@"Blarg"];
    }else{
        [self.daLabel setStringValue:@"Bloog"];
    }
}
@end

回答1:


For that you have to use NSNotificationCenter.

in Appdelegate use following code.

 [[NSNotificationCenter defaultCenter] postNotificationName:@"ChangeThelabel" object:nil];

use the below code in the init method of the implementation of the class that has the label.

  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(ChangelabelText:) name:@"ChangeThelabel" object:nil];

And in the same class use the following function.

- (void)ChangelabelText:(NSNotification *)notification
{
   // Change the text here.
}


来源:https://stackoverflow.com/questions/20910467/changing-the-value-of-nstextfield-doesnt-update-label

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!