【问题标题】:UICollectionViewCell is not rounding cornerUICollectionViewCell 不是圆角
【发布时间】:2019-08-26 03:23:42
【问题描述】:

我试图使角落变圆,但是当我使用cornerRadius和maskToBouds时,它不起作用

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath)
        cell.contentView.layer.cornerRadius = 30
        cell.contentView.layer.masksToBounds = true
        return cell
    }

单元格:

【问题讨论】:

  • 你试过 clipsToBound = true 吗?
  • 我已经试过了!没有成功
  • 你试过给 imageView 赋予 clipsToBounds = true 吗??

标签: ios swift xcode uicollectionviewcell cornerradius


【解决方案1】:

试试willDisplay:forItemAt:

例如

func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
        cell.layer.cornerRadius = 30
        cell.clipsToBounds = true
    }

【讨论】:

  • 它成功了,但它没有像预期的那样四舍五入!我的意思是,顶部仍然平坦!
  • 设置 image.contentMode = .scaleAspectFit
【解决方案2】:

不要设置cell'scontentView'scornerRadius,而是更改cell本身的cornerRadius,即

cell.layer.cornerRadius = 30
cell.clipsToBounds = true

请像上面的代码一样将cellclipsToBounds 设置为true

建议:

如果您想在collectionView 中设置每个cellcornerRadius,而不是在collectionView(_:cellForItemAt:) 方法中进行设置,而是在自定义UICollectionViewCellawakeFromNib() 方法中进行设置,即

class CustomCell: UICollectionViewCell {
    override func awakeFromNib() {
        super.awakeFromNib()
        self.layer.cornerRadius = 30
        self.clipsToBounds = true
    }
}

这是因为,由于collectionView(_:cellForItemAt:) 方法被多次执行,在那里编写布局代码有点低效。

【讨论】:

  • 它也有效,但顶角仍然平坦!就像这样:imgur.com/a/33vdu5k
  • 你指的是灰色的部分吗?那是collectionView还是cell?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-01-08
  • 1970-01-01
  • 1970-01-01
  • 2017-02-09
  • 2017-12-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多