更改 NSTextField 的值不会更新标签?



我正在尝试更改AppDelegate的标签。我可以使用在具有标签的类的实现中运行changeLabelIBAction更改标签,但是如果我尝试从AppDelegate运行changeLabel,它会更改值(我有一个 NSLog),但不更新标签。

代码如下:

#import <Foundation/Foundation.h>
@interface testLabelThingy : NSObject
@property (strong) IBOutlet NSTextField *daLabel;
- (id) init;
- (void)changeLabel;
- (IBAction)daButton:(id)sender;
@end

和:

#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

为此,您必须使用 NSNotificationCenter .

Appdelegate使用以下代码。

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

在具有标签的类的实现的 init 方法中使用以下代码。

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

并在同一类中使用以下函数。

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

最新更新