【问题标题】:Xcode OSX, bind NSString to UILabelXcode OSX,将 NSString 绑定到 UILabel
【发布时间】:2014-10-03 12:40:09
【问题描述】:

我有一个这样的模型类:

标题:

@interface RTSecurityModel : NSObject
{
    NSString *code;
}

@property NSString *code;

@end

实施:

@implementation RTSecurityModel

@synthesize code;

@end

然后我有我的应用代理:

标题:

@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 中使用“Model Key Path: security.code”设置“Bind To: App Delegate”。

但是当我启动我的应用程序时什么都没有显示。

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

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

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

这里是如何通过编辑文本字段来设置属性和标签值的示例

但是有没有办法在不编辑文本字段的情况下编辑标签?还是根本没有文本字段?

UPD2

您不能创建另一个 Object 实例

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

非常感谢维克多·列克星敦

【问题讨论】:

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


    【解决方案1】:

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

    Here 是一个演示项目。

    不要绑定Text Field Cell,使用Text Field

    如果您用文本填充Null Placeholder,您可以检查值是否为空,它会显示该文本吗?然后在绑定值的时候它为空。

    要在 Interface Builder 中看到你的 RTSecurityModel,你必须让它知道你的类,它不会寻找它。

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


    我可以想出两种方法在不使用 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 使用自定义setter(@synthesize 仍会为您创建getter)

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

    【讨论】:

    • 天哪,我确实认为,创建 Cocoa Bindings 是为了完全避免编码……但似乎并非如此 :(
    • @SergeVelikanov 哦,好吧,您只想在 Interface Builder 中创建绑定。也许模型键路径是错误的字段。你试过 value 字段吗?
    • @SergeVelikanov 我试过了,它奏效了。更新了答案。您需要将绑定目标更改为 RTSecurityModel 类。
    • 非常感谢维克托!但我在绑定选项卡中看不到 RTSecurityModel :( cdn.joxi.ru/uploads/prod/2014/08/10/b42/3c5/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多