0

我是材料设计的新手。我有自定义 collectionView 单元格Main.storyboard,其中包含一些标签、按钮和 Imageview。我想将我的自定义单元格加载为MDCCardCollectionCell.

当我使用此代码时,我得到了空的MDCCardCollectionCell. 它使应用程序崩溃

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
}

当我在没有此行的情况下加载自定义 collectionView 单元格时,它已成功加载,Main.storyboardMDCCard样式未应用(阴影效果)。

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

谢谢

4

2 回答 2

2

以下应该工作:

迅速:

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
}

对象:

[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];
}
于 2020-03-08T19:55:32.680 回答
0

您可以从 MDCCardCollectionCell 子类化您的 collectionViewCell,然后使用它。

于 2018-08-04T08:07:02.980 回答