首页 > 解决方案 > 如何使我的单元格像 App Store 中一样圆润

问题描述

截屏

我制作了 CollectionViewCells,我希望角落像 App Store 单元格一样圆润。我为背景设置了不同的颜色以更好地查看它。也尝试对图像视图做同样的事情

在下面的代码中,我试图使角变圆,但不要改变。

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    // setup the cell and cast it to the custom cell created.
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCell
    cell.elementNameLabel.text = elemementName[indexPath.row]
    cell.elementDescriptionLabel.text = elementDescription[indexPath.row]
    cell.elementImage.image = elementImage[indexPath.row]

    // Create the shadows and modify the cards
    cell.contentView.layer.cornerRadius = 10.0
    cell.contentView.layer.borderWidth = 1.0
    cell.contentView.layer.borderColor = UIColor.clear.cgColor
    cell.contentView.layer.masksToBounds = false
    cell.layer.shadowColor = UIColor.gray.cgColor
    cell.layer.shadowOffset = CGSize(width: 0, height: 1.0)
    cell.layer.shadowRadius = 4.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
}

标签: iosswiftcollectionsviewuicollectionview

解决方案


一旦你在 cell.layer 上设置了cornerRadius(就像你一样),你只需要将 maskToBounds 设置为 true,因为这就是告诉它遵守现在圆角的原因。(也不需要在contentView上设置隐形边框)

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    // setup the cell and cast it to the custom cell created.
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCell
    cell.elementNameLabel.text = elemementName[indexPath.row]
    cell.elementDescriptionLabel.text = elementDescription[indexPath.row]
    cell.elementImage.image = elementImage[indexPath.row]

    // Create the shadows and modify the cards
    cell.layer.shadowColor = UIColor.gray.cgColor
    cell.layer.shadowOffset = CGSize(width: 0, height: 1.0)
    cell.layer.shadowRadius = 4.0
    cell.layer.shadowOpacity = 1.0
    cell.layer.masksToBounds = true
    cell.layer.shadowPath = UIBezierPath(roundedRect: cell.bounds, cornerRadius: cell.contentView.layer.cornerRadius).cgPath

    return cell
}

推荐阅读