【问题标题】:Keyboard focus on NSCollectionView when app launches应用程序启动时键盘焦点在 NSCollectionView
【发布时间】:2018-09-08 22:34:36
【问题描述】:
当我的 Mac 应用程序启动或切换选项卡时,我试图将键盘焦点放在我的 NSCollectionView 上。我已尝试将其设为 firstResponder,它说是在我测试时,但我必须先在集合视图内单击,然后才能使用箭头键在集合视图项中导航。
@IBOutlet weak var collectionView: NSCollectionView!
override func viewDidAppear() {
self.collectionView.item(at: 0)?.isSelected = true
self.collectionView.becomeFirstResponder()
}
我也尝试将它放在 viewDidAppear 覆盖中,但没有骰子。
有人有同样的问题吗?你是怎么解决的?
【问题讨论】:
标签:
swift
macos
nscollectionview
【解决方案1】:
根据我的经验,NSCollectionView 不允许您使用箭头键导航,除非已经选择了某个项目。所以我通过继承 NSCollectionView.becomeFirstResponder() 并在未选择任何内容时手动选择第一个可用项目来做到这一点。
class MyCollectionView: NSCollectionView {
override func becomeFirstResponder() -> Bool {
if selectionIndexPaths.count == 0 {
for section in 0..<numberOfSections {
if numberOfItems(inSection: section) > 0 {
selectionIndexPaths = [IndexPath(item: 0, section: section)]
break
}
}
}
return super.becomeFirstResponder()
}
}
【解决方案2】:
我这样做了:
self.collectionView.reloadData()
if let selectionIndexPath = self.selectionIndexPath {
self.collectionView.selectItems(at: [selectionIndexPath],
scrollPosition: .centeredVertically)
self.view.window?.makeFirstResponder(self.collectionView)
}
NSCollectionView 以这种方式获得焦点。 (在 Mac OS 10.15.4 上测试)。
收到后端响应后,我重新加载了数据。