为什么我的UICollectionViewCell不带阴影四舍五入?

时间:2018-10-04 04:24:49

标签: ios swift uicollectionview uicollectionviewcell

我遵循了:https://stackoverflow.com/a/25493235https://stackoverflow.com/a/44820559,但是如果不执行cell.layer.cornerRadius = X而不是cell.contentView.layer.cornerRadius = X

,就无法使单元格四舍五入

这是我在collectionView中定义单元格的函数代码:

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath as IndexPath) as! CustomCollectionCell
    cell.backgroundColor = UIColor.white
    cell.contentView.layer.cornerRadius = 2.0
    cell.contentView.layer.borderWidth = 1.0
    cell.contentView.layer.borderColor = UIColor.clear.cgColor
    cell.contentView.layer.masksToBounds = true

    cell.layer.shadowColor = UIColor.lightGray.cgColor
    cell.layer.shadowOffset = CGSize(width: 0, height: 2.0)
    cell.layer.shadowRadius = 2.0
    cell.layer.shadowOpacity = 1.0
    cell.layer.masksToBounds = false
    cell.layer.shadowPath = UIBezierPath(roundedRect: cell.bounds, cornerRadius: cell.contentView.layer.cornerRadius).cgPath
    return cell
}

在尝试对单元进行四舍五入之前,我只拥有该函数中的cell.backgroundColor = UIColor.white,因此,我现在所拥有的只是来自StackOverflow的代码,因为我想对其进行测试。任何帮助将不胜感激。

现在看起来像这样:

enter image description here

这与Pratik的建议类似:

enter image description here

更新

我想没有其他方法可以做到:

  1. 清除cell.backgroundColor并将contentView设为白色

  1. 使该单元格不包含背景色,而将contentView设为白色。

2 个答案:

答案 0 :(得分:0)

更新 就您而言,只需

    cell.layer.shadowColor = UIColor.lightGray.cgColor
    cell.layer.shadowOffset = CGSize(width: 0, height: 2.0)
    cell.layer.shadowRadius = 2.0
    cell.layer.shadowOpacity = 1.0
    cell.layer.masksToBounds = true
    cell.layer.shadowPath = UIBezierPath(roundedRect: cell.bounds, 
    cornerRadius: cell.contentView.layer.cornerRadius).cgPath

    cell.backgroundColor = UIColor.white
    cell.contentView.layer.cornerRadius = 2.0
    cell.contentView.layer.borderWidth = 1.0
    cell.contentView.layer.borderColor = UIColor.clear.cgColor
    cell.contentView.layer.masksToBounds = false
    cell.backgroundColor = //background color of your collection view or your main view.

答案 1 :(得分:-1)

您可以使用以下代码:

cell.contentView.layer.shadowColor = hexStringToUIColor(hex: "#000000").cgColor
cell.contentView.layer.masksToBounds = true
cell.contentView.layer.shadowOpacity = 0.3
cell.contentView.layer.shadowOffset = CGSize.zero
cell.contentView.layer.shadowRadius = 2
cell.contentView.layer.shouldRasterize = true
cell.contentView.layer.rasterizationScale = true ? UIScreen.main.scale : 1