MacアプリのNSCollectionViewでクリックしたItemを取得する
Macアプリ の NSCollectionView で、クリックした NSCollectionViewItem を取得します。
iOS アプリとほとんどおなじで、 NSCollectionViewDelegate に定義されている collectionView(_:didSelectItemsAt:) メソッドを使います。
code: Swift
extension ViewController: NSCollectionViewDelegate {
func collectionView(_ collectionView: NSCollectionView, didSelectItemsAt indexPaths: Set<IndexPath>) {
guard let indexPath = indexPaths.first else {
return
}
print("\(indexPath.item)")
}
}
iOS と異なるのは、 indexPath が Set になっていることです。
ひとつの Item だけを選択する場合は、 first で最初の indexPath を取得してつかいます。
https://gyazo.com/31aa861e2b9202c370daa302c4dfd1de
あとは、ストーリーボードで、 CollectionView の Attribute Inspector にある Selection の Selectable にチェックを入れると、クリックした Item の indexPath を取得できます。
あ、そうそう。
NSCollectionView の indexPath は、 section と item です。iOS の row にあたるのが item です。