如何使用MDCCardCollectionCell?[材料组件iOS]



我是材料设计的新手。我在Main.storyboard中有自定义的collectionView单元格,其中包含一些标签、按钮和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.storyboard成功加载,但MDCCard样式未应用(阴影效果(。

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

感谢

以下内容应该有效:

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
}

目标:

[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];
}

您可以从MDCCardCollectionCell中对collectionViewCell进行子类化,然后使用它。

最新更新