How to use MDCCardCollectionCell? [Material components iOS]

1.1k Views Asked by At

I'm new to Material design. I have custom collectionView cells in Main.storyboard, which contains some labels, buttons and Imageview. I want to load my custom cell as MDCCardCollectionCell.

When i use this code, I'm getting the empty MDCCardCollectionCell. It crashes the Application

collectionView.register(MDCCardCollectionCell.self, forCellWithReuseIdentifier: "Cell")

func collectionView(_ collectionView: UICollectionView,
                    cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell",
                                                for: indexPath) as! MDCCardCollectionCell

  cell.cornerRadius = 8
  cell.setShadowElevation(6, for: .selected)
  cell.setShadowColor(UIColor.black, for: .highlighted)
  return cell
}

When i load custom collectionView cells without this line its loaded successfully from Main.storyboard but the MDCCard styles is not applying (shadow effect).

collectionView.register(MDCCardCollectionCell.self, forCellWithReuseIdentifier: "Cell")

Thanks

2

There are 2 best solutions below

0
On

You can subclass your collectionViewCell from MDCCardCollectionCell and then use it.

0
On

Following should work:

Swift:

collectionView.register(MDCCardCollectionCell.self, forCellWithReuseIdentifier: "Cell")

func collectionView(_ collectionView: UICollectionView,
                    cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell",
                                                for: indexPath) as! MDCCardCollectionCell
  // If you wanted to have the card show the selected state when tapped
  // then you need to turn isSelectable to true, otherwise the default is false.
  cell.isSelectable = true

  cell.selectedImageTintColor = .blue
  cell.cornerRadius = 8
  cell.setShadowElevation(6, for: .selected)
  cell.setShadowColor(UIColor.black, for: .highlighted)
  return cell
}

Objc:

[self.collectionView registerClass:[MDCCardCollectionCell class]
        forCellWithReuseIdentifier:@"Cell"];

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
                  cellForItemAtIndexPath:(NSIndexPath *)indexPath {
  MDCCardCollectionCell *cell =
  [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell"
                                            forIndexPath:indexPath];
  // If you wanted to have the card show the selected state when tapped
  // then you need to turn selectable to true, otherwise the default is false.
  [cell setSelectable:YES];

  [cell setSelectedImageTintColor:[UIColor blueColor]];
  [cell setCornerRadius:8];
  [cell setShadowElevation:6 forState:MDCCardCellStateSelected];
  [cell setShadowColor:[UIColor blackColor] forState:MDCCardCellStateHighlighted];
}