如何为TableView和CollectionView创建可重用的单元格

时间:2020-12-20 00:01:55

I have a TableView and a CollectionView in different ViewController. Now I am showing an exactly same cell in both of them. So I want to create a reusable cell for convenience and easy maintenance.

我在不同的ViewController中有一个TableView和一个CollectionView。现在我在两个中显示完全相同的单元格。因此,我想创建一个可重复使用的单元,以方便和维护。

I tried to create a xib and set the custom class to an UITableViewCell class, then I can register and load it in the UITableView. However, I cannot reuse this xib in the UICollectionView because CollectionView cannot load TableViewCell.

我尝试创建一个xib并将自定义类设置为UITableViewCell类,然后我可以在UITableView中注册并加载它。但是,我无法在UICollectionView中重用此xib,因为CollectionView无法加载TableViewCell。

So my question is that is there any good way to make a reusable cell for both TableView and CollectionView?

所以我的问题是,有没有什么好的方法可以为TableView和CollectionView创建一个可重用的单元格?

1 个解决方案

#1


2  

UITableViewCell <- UIView

UICollectionViewCell <- UICollectionReusableView <- UIView

both are from UIView, so i think you can create a xib for UIView, and use that view in your UITableViewCell and UICollectionViewCell. Eg: How to load a xib file in a UIView

两者都来自UIView,所以我认为你可以为UIView创建一个xib,并在你的UITableViewCell和UICollectionViewCell中使用该视图。例如:如何在UIView中加载xib文件

and since both cell are going to have common code for some cases you can use category, to share the common code Eg: Sharing code between UITableViewCell and UICollectionViewCell

并且因为两个单元格都有一些公共代码用于某些情况,你可以使用类别,共享公共代码例如:在UITableViewCell和UICollectionViewCell之间共享代码

#1


2  

UITableViewCell <- UIView

UICollectionViewCell <- UICollectionReusableView <- UIView

both are from UIView, so i think you can create a xib for UIView, and use that view in your UITableViewCell and UICollectionViewCell. Eg: How to load a xib file in a UIView

两者都来自UIView,所以我认为你可以为UIView创建一个xib,并在你的UITableViewCell和UICollectionViewCell中使用该视图。例如:如何在UIView中加载xib文件

and since both cell are going to have common code for some cases you can use category, to share the common code Eg: Sharing code between UITableViewCell and UICollectionViewCell

并且因为两个单元格都有一些公共代码用于某些情况,你可以使用类别,共享公共代码例如:在UITableViewCell和UICollectionViewCell之间共享代码