上下文-
我正在使用macOS菜单栏应用程序,该应用程序显示项目的集合。这些项目存在于集合视图中,并包含一个文本字段。
现在,集合视图的布局固定为50的高度,我正在尝试根据文本字段的大小动态增加单元格的大小。
我相信最好的方法是在sizeForItemAt
方法中,但是我似乎无法引用一个单元格及其文本字段来计算并返回其高度。此时,只要我尝试获取collectiomView项,应用程序就会崩溃,并显示[General] *** -[__NSArrayM objectAtIndex:]: index 1 beyond bounds [0 .. 0]
异常。
我的代码-
我的viewDidLoad,在这里“配置”我的CollectionView
override func viewDidLoad() {
super.viewDidLoad()
configureCollectionView()
....
}
private func configureCollectionView() {
let flowLayout = NSCollectionViewFlowLayout()
flowLayout.itemSize.width = self.view.frame.width
flowLayout.minimumLineSpacing = 8
thoughtsCollectionView.collectionViewLayout = flowLayout
view.wantsLayer = true
}
这是我试图动态设置高度(以及崩溃的位置)
func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> NSSize {
guard collectionView.item(at: indexPath) != nil else { // <-- CRASHES HERE
return NSSize(width: self.view.frame.width, height: 50)
}
return self.collectionView.item(at: indexPath)?.textField?.frame.height
}
这是我将项目添加到collectionView的方式>>
func collectionView(_ collectionView: NSCollectionView, itemForRepresentedObjectAt indexPath: IndexPath) -> NSCollectionViewItem { let item = collectionView.makeItem(withIdentifier: "CollectionViewItem", for: indexPath as IndexPath) guard let collectionViewItem = item as? CollectionViewItem else {return item} (item as! CollectionViewItem).textField?.stringValue = "Some Text" (item as! CollectionViewItem).delegate = self return item }
所以对我来说奇怪的是,在我的
collectionView(_ collectionView: NSCollectionView, didSelectItemsAt indexPaths: Set<IndexPath>)
中,我要通过做来成功获得该物品
func collectionView(_ collectionView: NSCollectionView, didSelectItemsAt indexPaths: Set<IndexPath>) { guard let indexPath = indexPaths.first else { return } guard collectionView.item(at: indexPath) != nil else { return } let item = collectionView.item(at: indexPath) as! CollectionViewItem // <--- This gets me an item fine
所以我不确定为什么要为
sizeForItemAt
苦苦挣扎。我有一种感觉,因为这些项目尚不存在(当视图开始显示它们时会创建它们),但是不确定如何正确处理此动态大小。
上下文-我正在使用macOS菜单栏应用程序,该应用程序显示项目的集合。这些项目存在于集合视图中,并包含一个文本字段。现在,集合视图的布局是固定的...
我遇到相同的问题。通过阅读文档,我发现Apple打算让我们使用NSCollectionViewLayout
代替项目。