SWIFT - cornerRadius 在自定义 CollectionViewCell 中不起作用

SWIFT - cornerRadius is not working in custom CollectionViewCell

我试图获取圆形的 UICollection 单元格,但我发现它无法正常工作,我也想不出原因。我在常规 ViewController 中有一个 TableView,在这个 table 视图中我有一个自定义 table 单元格(在指定部分),在这个自定义 table 单元格中我有一个CollectionView 也带有自定义 collectionCell,如果我在那里做任何四舍五入,它就不会四舍五入。我将 testBtn 夹在边界内,但它不适用于此...我也尝试 testBtn.layer.masksToBounds 但没有成功。但是,如果我在父级(table查看单元格本身)中进行舍入,它工作得很好...

CollectionViewCell 代码:

import UIKit

class ProfileTileCollectionViewCell: UICollectionViewCell {

    @IBOutlet var testBtn: UIButton!
    @IBOutlet var contView: UIView!

    override func awakeFromNib() {
        super.awakeFromNib()
        testBtn.layer.cornerRadius = 20
        testBtn.clipsToBounds = true
        // Initialization code
    }

    @IBAction func testClicked(_ sender: Any) {
        print("clicked")
    }
}

主视图的屏幕截图:Screenshot.png

蓝色是collectionView的背景,灰色是单元格的背景,紫色是按钮。我不知道是不是已经晚了,但这对我来说很奇怪,无法开始工作......我错过了一些东西......我将不胜感激!

尝试设置 testBtn.layer.masksToBounds = true

从屏幕截图来看,我猜您已经在集合视图中添加了圆角半径并将 clipsToBounds 设置为 true。如果您不需要圆形集合视图,请删除 cornerRadius 并将 clipsToBounds 设置为 false。或者,如果您需要将它们都圆化,则在集合视图和按钮之间保持填充。您可以通过微调部分插图 属性.

来做到这一点

我睡了 8 个小时,因为那个和 Rob 的评论,我试图深入调试一下,我注意到一条警告消息,说 UICollectionViewFlowLayout 的行为未设置...(等等)。所以我决定像这样设置 UICollectionViewDelegateFlowLayout:

extension ProfileTilesTableViewCell: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
    return UIEdgeInsets(top:0, left:10, bottom:0, right: 10)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return CGSize(width: (collectionView.frame.width - 40) / 3 , height: collectionView.frame.height - 5)
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
    return 10
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
    return 10
}

最后 :D 它开始正常工作了!

所以我删除了用于测试的所有内容,删除了 testBtn 并将 testBtn.roundedCorners 更改为 contView.roundedCorners,设置回 collectionView 属性,它看起来接近我正在寻找的内容:Screenshot2.png

感谢您的回答,尤其是 Rob 的回答。这就是我要找的!

问候 SB!