将NSPopupbutton绑定到一个类数组

时间:2018-12-30 17:20:49

标签: swift binding nsarraycontroller nspopupbutton

我在将NSPopUpButton绑定到NSArrayController时遇到困难。 数组控制器管理类Plant的一个数组(植物),该数组具有一个名为commonName的属性,该属性应在按钮中列出。我已经搜索了几天,但无法找到为什么这行不通。我能够获得显示字符串数组元素的按钮,但不能显示plants数组。程序运行时,按钮没有任何元素,对单击没有反应。

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

ArrayController

  1. 属性:Mode = Class;类名称= TestDB.Plant(TestDB是 项目名称)
  2. 绑定:绑定到View Controller;型号键     路径=植物

按钮绑定

  1. 内容:绑定到阵列控制器;控制器键=布置对象
  2. 内容值:绑定到数组控制器;控制器键= rangedObjects;模型键路径= 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
    }   
}

这是Plant类的代码:

@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的属性和绑定的屏幕截图。非常感谢您的帮助。

Attributes and Bindings

1 个答案:

答案 0 :(得分:1)

两项更改:

  1. 您必须使plants也符合KVC

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

相关问题