Fer*_*ios 5 macos nscollectionview swift
我已经在我的 Mac 应用程序中成功实现了 10.11 版本的 NSCollectionView。它显示了我想要的 10 个项目,但我希望在应用程序启动时自动选择第一个项目。
我在 viewDidLoad 和 viewDidAppear 函数中尝试了以下操作;
let indexPath = NSIndexPath(forItem: 0, inSection: 0)
var set = Set<NSIndexPath>()
set.insert(indexPath)
collectionView.animator().selectItemsAtIndexPaths(set, scrollPosition: NSCollectionViewScrollPosition.Top)
Run Code Online (Sandbox Code Playgroud)
我已经尝试过上面的第 4 行,无论有没有动画师
我还尝试了以下方法来代替第 4 行
collectionView.animator().selectionIndexPaths = set
Run Code Online (Sandbox Code Playgroud)
有和没有 animator()
虽然它们都在选定的索引路径中包含索引路径,但实际上都没有将项目显示为选定的。
有什么线索我哪里出错了吗?
我建议不要使用滚动位置。在 Swift 3 中,viewDidLoad 中的以下代码对我有用
// select first item of collection view
collectionView(collectionView, didSelectItemsAt: [IndexPath(item: 0, section: 0)])
collectionView.selectionIndexPaths.insert(IndexPath(item: 0, section: 0))
Run Code Online (Sandbox Code Playgroud)
第二行代码是必需的,否则该项目永远不会被取消选择。以下也有效
collectionView.selectItems(at: [IndexPath(item: 0, section: 0)], scrollPosition: NSCollectionViewScrollPosition.top)
Run Code Online (Sandbox Code Playgroud)
对于这两个代码片段,必须有一个带有该函数的 NSCollectionViewDelegate
func collectionView(_ collectionView: NSCollectionView, didSelectItemsAt indexPaths: Set<IndexPath>) {
// if you are using more than one selected item, code has to be changed
guard let indexPath = indexPaths.first
else { return }
guard let item = collectionView.item(at: indexPath) as? CollectionViewItem
else { return }
item.setHighlight(true)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3110 次 |
| 最近记录: |