Как использовать MDCCardCollectionCell? [Материал компонентов iOS]
Я новичок в дизайне материалов. У меня есть пользовательские ячейки 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.storyboard
но MDCCard
стили не применяются (эффект тени).
collectionView.register(MDCCardCollectionCell.self, forCellWithReuseIdentifier: "Cell")
Спасибо
1 ответ
Следующее должно работать:
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];
}
Вы можете создать подкласс вашего collectionViewCell из MDCCardCollectionCell и затем использовать его.