7

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.

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.

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

Amal T S
  • 3,327
  • 2
  • 24
  • 57
shippo7
  • 407
  • 5
  • 15

1 Answers1

4
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

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

Amal T S
  • 3,327
  • 2
  • 24
  • 57
Gokul G
  • 698
  • 4
  • 11
  • This solution is working. However, it will break the automatic dimension on UITableView. We need to add constraints for the subviews of cell.contentView programmatically to keep the automatic dimension working. http://stackoverflow.com/questions/27294328/ios-8-uitableviewcell-contentview-doesnt-resize-subviews-in-it – shippo7 Jan 23 '17 at 18:42