如何在App Store中将单元格四舍五入

时间:2019-07-03 22:19:15

标签: ios swift collections view uicollectionview

Screenshot

我制作了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
}

2 个答案:

答案 0 :(得分:0)

一旦在cell.layer上设置了CornerRadius(如您所愿),您只需要将masksToBounds设置为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
}

答案 1 :(得分:0)

您可以在单元格上添加一个四舍五入的视图,然后在该视图上放置其他内容。