我已经成功地在我的苹果应用程序中实现了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)
我已经尝试了上面的第四行,有没有动画师
我还尝试了下面的代码来代替第4行
collectionView.animator().selectionIndexPaths = set
使用和不使用动画师()
虽然它们都将索引路径包含在选定的索引路径中,但它们都不会将项目实际显示为选定项。
我哪里出错了,有什么线索吗?
发布于 2017-03-08 05:40:53
我建议不使用滚动位置。在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))
第二个代码行是必需的,否则永远不会取消选择该项。下面的方法也是有效的
collectionView.selectItems(at: [IndexPath(item: 0, section: 0)], scrollPosition: NSCollectionViewScrollPosition.top)
对于这两个代码片段,都必须有一个带有函数的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)
}
发布于 2019-12-16 11:58:18
根据苹果公司的文件,使用NSCollectionView
的方法编程选择项目不会调用NSCollectionViewDelegate
的didSelect方法,所以你必须自己添加亮点。
override func viewDidAppear() {
super.viewDidAppear()
retainSelection()
}
private func retainSelection() {
let indexPath = IndexPath(item: 0, section: 0)
collectionView.selectItems(at: [indexPath], scrollPosition: .nearestVerticalEdge)
highlightItems(true, atIndexPaths: [indexPath])
}
private func highlightItems(_ selected: Bool, atIndexPaths: Set<IndexPath>) {
for indexPath in atIndexPaths {
guard let item = collectionView.item(at: indexPath) else {continue}
item.view.layer?.backgroundColor = (selected ? NSColor(named: "ItemSelectedColor")?.cgColor : NSColor(named: "ItemColor")?.cgColor)
}
}
发布于 2020-05-09 00:06:08
我认为您可以使用view.layer来显示选择状态。而且看起来NSCollectionViewItem目前还没有分层。如果您创建了NSCollectionViewItem子类,请尝试在viewDidLoad方法中启用其视图的wantsLayer属性。
override func viewDidAppear() {
super.viewDidLoad()
self.view.wantsLayer = true
}
您也可以在func collectionView(NSCollectionView,itemForRepresentedObjectAt: IndexPath) -> NSCollectionViewItem中启用wantsLayer。
func collectionView(collectionView: NSCollectionView, itemForRepresentedObjectAtIndexPath
indexPath: NSIndexPath) -> NSCollectionViewItem {
let item = self.collectionView.makeItemWithIdentifier("dataSourceItem", forIndexPath: indexPath)
// Configure the item ...
item.view.wantsLayer = true
return item
}
然后你就可以调用
collectionView.selectionIndexPaths = set
并确保它能正常工作。
https://stackoverflow.com/questions/35207364
复制相似问题