UIViewController xib文件包含具有自定义单元格的collectionview

时间:2018-12-18 18:03:07

标签: ios swift uicollectionview uicollectionviewcell xib

我有一个xib文件,其中包含一个名为UIViewController的{​​{1}}。它包含一个FullScreenGalleryVC,其中包含一个自定义UICollectionView,其标识符为UICollectionViewCell

当我想创建一个新的fullscreen_cell时,我打电话给FullScreenGalleryVC

这是功能:

FullscreenGalleryVC.display(from: self)

我收到此错误:

  

无法使以下类型的视图出队:UICollectionElementKindCell与   标识符fullscreen_cell-必须注册笔尖或类   标识符或连接情节提要中的原型单元格


如果我将自定义单元格放在另一个xib文件中并调用class func display(from sourcevc:UIViewController){ let vc=UINib(nibName: "FullscreenGalleryVC", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! FullscreenGalleryVC sourcevc.present(vc, animated: true, completion: nil) } ,效果很好。

如果我不将此register(nibClass, forCellWithReuseIdentifier: cellId)类放在单独的xib文件中(并将其保存在我的主故事板上),则效果很好。


但是我在应用程序和操作扩展中都使用了此类,所以这就是为什么我想使用通用文件而不是复制所有内容。 有没有办法做到这一点,或者我必须将自定义单元放置在另一个xib文件中才能使其正常工作?

enter image description here

1 个答案:

答案 0 :(得分:1)

如果您是FullScreenGalleryVC控制器的xib文件,则应使用register(nibClass, forCellWithReuseIdentifier: cellId)告诉集合视图如何创建给定类型的新单元格。

let cellNib = UINib(nibName: "FullScreenGalleryCell", bundle: .main) 
collectionView.register(cellNib, forCellWithReuseIdentifier: "fullscreen_cell")

如果使用storyboard,则集合视图已使用指定的cellId知道了它。

我认为,您可以将storyboard使用FullScreenGalleryVC并将其重用于其他类。

通过特定的storyboard(例如,

)提供一个viewController
let storyboard = UIStoryboard(name: "YourStoryboardName", bundle: nil)
let controller = storyboard.instantiateViewController(withIdentifier: "storyboardId")
self.present(controller, animated: true, completion: nil)

image 1 image 2

相关问题