【问题标题】:binding NSPopupbutton to an array of classes将 NSPopupbutton 绑定到类数组
【发布时间】:2018-12-30 17:20:48
【问题描述】:

我很难将 NSPopUpButton 绑定到 NSArrayController。 数组控制器管理类 Plant 的数组(植物),该数组有一个名为 commonName 的属性,该属性应列在按钮中。我已经搜索了几天,但我无法发现为什么这不起作用。我能够获得按钮来显示字符串数组的元素,但不能使用植物数组。程序运行时,按钮没有元素,对点击没有反应。

我已经包含了属性和绑定的屏幕截图,但这里有一个描述:

数组控制器

  1. 属性:模式 = 类;类名 = TestDB.Plant(TestDB 是 项目名称)
  2. 绑定:绑定到视图控制器;型号键 路径 = 植物

按钮绑定

  1. 内容:绑定到阵列控制器;控制器键 = 排列对象
  2. 内容值:绑定到阵列控制器;控制器键 = 排列对象;模型键路径 = objectValue.commonName

这是来自 ViewController 的代码:

class ViewController: NSViewController {

@IBInspectable var plants: [Plant] = []
@IBOutlet weak var plantPopUp: NSPopUpButton!

    override func viewDidLoad() {
            super.viewDidLoad()

        //the real list will be pulled from a database, but I'm using
        //this to test binding the button
        plants = [Plant(commonName: "Asparagus", scientificName: "Asparagus officials"), 
          Plant(commonName: "Beet", scientificName: "Beta vulgaris")]

        //to redraw the button?? Doesn't change anything with or without
        plantPopUp.needsLayout.true
    }   
}

这是植物类的代码:

@objc class Plant: NSObject {
    @objc dynamic var commonName: String
    @objc dynamic var scientificName: String

    init(commonName: String, scientificName: String) {
        self.commonName = commonName
        self.scientificName = scientificName
    }
}

这里是 NSArrayController 和 NSPopupButton 的属性和绑定的截图。非常感谢您的帮助。

【问题讨论】:

    标签: swift binding nsarraycontroller nspopupbutton


    【解决方案1】:

    两个变化:

    1. 你必须让plants也符合KVC

      @IBInspectable @objc dynamic var plants: [Plant] = []
      
    2. 按钮绑定 - 内容值:绑定到 ... 模型键路径 = commonName(删除 objectValue.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-11-01
      • 1970-01-01
      • 2015-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多