Xcode OSX,将NSString绑定到UILabel

时间:2014-08-10 16:10:12

标签: objective-c xcode macos cocoa cocoa-bindings

我有一个像这样的模型类:

部首:

@interface RTSecurityModel : NSObject
{
    NSString *code;
}

@property NSString *code;

@end

实现:

@implementation RTSecurityModel

@synthesize code;

@end

然后我有我的App代表:

部首:

@interface RTAppDelegate : NSObject <NSApplicationDelegate>
{
    RTSecurityModel *security;
}

@property (assign) IBOutlet NSWindow *window;

@property RTSecurityModel *security;

@end

实现:

@implementation RTAppDelegate

@synthesize security;

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    security = [[RTSecurityModel alloc] init];
    security.code = @"test";
}

然后在我的MainMenu.xib中我创建了一个标签,并在Bindings Inspector中设置了“Bind To:App Delegate”和“Model Key Path:security.code”。

但是当我开始申请时,没有任何表现。

我尝试了很多方法来绑定这个变量,但是没有人成功。

请帮助我不要讨厌XCode和Cocoa!

UPD http://www.experts-exchange.com/Programming/Languages/C/A_3381-Simple-Binding-Cocoa-GUI-Application-without-Outlets.html

以下是如何通过编辑文本字段

来设置属性和标签值的示例

但有没有一种方法可以在不编辑文本字段的情况下编辑Label?或者根本没有文字字段?

UPD2

您不得创建另一个Object

实例
security = [[RTSecurityModel alloc] init]; // Kill this

很多感谢Viktor Lexington

1 个答案:

答案 0 :(得分:1)

不使用security.code作为模型路径,而是使用code。使用绑定选项卡的值部分中的类RTSecurityModel而不是AppDelegate。

Here是一个演示项目。

绑定Text Field Cell,请使用Text Field

如果您使用文字填充Null Placeholder,您可以检查某个值是否为空,是否会显示该文字?然后在绑定值时,它为null。

要在界面生成器中查看您的RTSecurityModel,您必须让它知道您的课程,它不会查找它。

添加一个Object,然后将其自定义类设置为RTSecurityModel。 然后,您可以选择此对象并将引用插座设置为App Delegate中的属性。 现在,分配将直接反映在标签中。

enter image description here


我可以想到两种在没有Interface Builder的情况下以编程方式解决此问题的方法:

  1. Key Value Coding

    // add an observer for the value on the object that has the method below implemented
    [self addObserver: self forKeyPath: @"security.code" options: NSKeyValueObservingOptionNew context: NULL];
    
    // method will be called when the observer has 'seen' a value change
    -(void) observeValueForKeyPath: (NSString *)keyPath ofObject: (id) object                  change: (NSDictionary *) change context: (void *) context {
        label.text = ...
    }
    
  2. code使用自定义设置器(@synthesize仍将为您创建获取器)

    - (void)setCode:(NSString *)aString {
        label.text = aString;
    }