我正在尝试更改AppDelegate
的标签。我可以使用在具有标签的类的实现中运行changeLabel
的IBAction
更改标签,但是如果我尝试从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.
}