【问题标题】:Make NSTextField update its bound value when setting its string value programmatically以编程方式设置其字符串值时,使 NSTextField 更新其绑定值
【发布时间】:2013-08-11 15:46:54
【问题描述】:

我有一个 NSTextField 绑定到用户默认值中的一个键。当我按下输入或离开该字段时,绑定值会正确更新(我有一个观察者)。但是,当我以编程方式设置文本字段的值时,绑定值不会更新。然而,文本字段显示了我设置的新字符串:

stockField1.stringValue = [sender representedObject];

(它是从菜单项处理程序中设置的)。是否有必要向文本字段发送额外的消息,或者我还能如何进行这项工作?

【问题讨论】:

    标签: cocoa cocoa-bindings nstextfield


    【解决方案1】:

    手动触发键值绑定如下:

    - (void)symbolSelected: (id)sender
    {
        NSTextField *field;
        switch ([sender tag]) {
            case 0:
                field = stockField1;
                break;
            case 1:
                field = stockField2;
                break;
            case 2:
                field = stockField3;
                break;
        }
    
        field.stringValue = [sender representedObject];
        NSDictionary *bindingInfo = [field infoForBinding: NSValueBinding];
        [[bindingInfo valueForKey: NSObservedObjectKey] setValue: field.stringValue
                                                      forKeyPath: [bindingInfo valueForKey: NSObservedKeyPathKey]];
    }
    

    【讨论】:

      【解决方案2】:

      这是迈克回答的 Swift 版本,供参考:

      guard
          let bindingInfo = self.infoForBinding(NSBindingName.value),
          let observedObject = bindingInfo[NSBindingInfoKey.observedObject] as? NSObject,
          let observedKeyPath = bindingInfo[NSBindingInfoKey.observedKeyPath] as? String else {
              return
      }
      
      observedObject.setValue(self.stringValue, forKeyPath: observedKeyPath)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-05-23
        • 2022-11-18
        • 1970-01-01
        • 2017-12-14
        • 1970-01-01
        • 2016-08-14
        • 1970-01-01
        • 2012-12-30
        相关资源
        最近更新 更多