如何使用 Xcode 12 在 macOS 程序的 Tableview 中为 NSComboBoxCell 编码数据源?

问题描述

我有一个带有 tableView 的测试应用程序,该应用程序为 Xcode 12 中的一列提供了一个 comboBoxCell:

The view controller code is as follows:

//
//  ViewController.swift
//  ComboBoxExample
//
//

import Cocoa

class ViewController: NSViewController,NSComboBoxCellDataSource {
    var states = ["Alabama","Alaska","Arizona","Arkansas","California","Colorado","Connecticut","Delaware","Florida","Georgia","Hawaii","Idaho","Illinois","Indiana","Iowa","Kansas","Kentucky","Louisiana","Maine","Maryland","Massachusetts","Michigan","Minnesota","Mississippi","Missouri","Montana","Nebraska","Nevada","New Hampshire","New Jersey","New Mexico","New York","north Carolina","north Dakota","Ohio","Oklahoma","Oregon","Pennsylvania","Rhode Island","South Carolina","South Dakota","Tennessee","Texas","Utah","Vermont","Virginia","Washington","West Virginia","Wisconsin","Wyoming"]
    // var itemCombo: NSComboBoxCellDataSource? = states
    @IBOutlet weak var itemComboCell: NSComboBoxCell!
    override func viewDidLoad() {
        super.viewDidLoad()
       
        itemComboCell.usesDataSource = true
        itemComboCell.dataSource = self
        self.itemComboCell.completes = true
        // Do any additional setup after loading the view.
    }

    override var representedobject: Any? {
        didSet {
        // Update the view,if already loaded.
        }
    }
    func numberOfItemsInComboBoxCell(in comboBoxCell: NSComboBoxCell) -> Int {
      // anArray is an Array variable containing the objects
        return states.count
    }
    func comboBoxCell(_ comboBoxCell: NSComboBoxCell,objectValueForItemAt index: Int) -> Any {
        return (states[index])
    }

}

运行示例时出现以下错误: 2021-03-05 15:16:29.940373-0600 ComboBoxExample[40515:1914724] *** 非法 NSComboBoxCell 数据源 ()。必须实现 numberOfItemsInComboBoxCell: 和 comboBoxCell:objectValueForItemAtIndex:

尝试使用以下内容设置数据源时我做错了什么: itemComboCell.dataSource = self

谢谢

下面是这个测试应用的故事板图片

enter image description here

解决方法

目标-C

- (NSInteger)numberOfItemsInComboBoxCell:(NSComboBoxCell *)comboBoxCell;

在 Swift 中

optional func numberOfItems(in comboBoxCell: NSComboBoxCell) -> Int

来源:numberOfItemsInComboBoxCell