Getting clicked item index in NSPathControl with pathItems instead of pathComponentCells

62 Views Asked by At

Since NSPathControl.setPathComponentCells(_:) and .clickedPathComponentCell() are deprecated, I'm trying to use pathItems and clickedPathItem instead. Since I'm representing a virtual path, I cannot use the NSPathControl.url setter, but instead set pathItems directly.

The problem is that in the action method it doesn't seem possible to get the index of the clicked path item, nor does it seem possible to associate any kind of data with each path item, since when the action method is called, the actual object instances stored in pathItems and also the one returned by clickedPathItem change every time. Here is the sample code that reproduces the issue:

class ViewController: NSViewController {

    @IBOutlet weak var pathControl: NSPathControl!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        pathControl.pathItems = ["a", "b", "c"].map({ title in
            let item = NSPathControlItem()
            item.title = title
            return item
        })
    }

    @IBAction func selectPath(_ sender: NSPathControl) {
        print(sender.clickedPathItem!.description, sender.clickedPathItem!.title, sender.pathItems.description)
    }
    
}

Here is a sample output (notice how the printed addresses change every time):

<NSPathControlItem: 0x6000012780a0> a [<NSPathControlItem: 0x6000012780a0>, <NSPathControlItem: 0x600001278020>, <NSPathControlItem: 0x600001278090>]
<NSPathControlItem: 0x600001278070> a [<NSPathControlItem: 0x600001278070>, <NSPathControlItem: 0x600001278140>, <NSPathControlItem: 0x6000012780d0>]
<NSPathControlItem: 0x60000124c030> a [<NSPathControlItem: 0x60000124c030>, <NSPathControlItem: 0x60000124c080>, <NSPathControlItem: 0x60000124c070>]
0

There are 0 best solutions below