如何设置 UICollectionviewCell

How can I set UICollectionviewCell

我在故事板的集合视图单元格中添加了一张图片。我想将图像设置为圆形。但是,它不起作用。

ViewController

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! ContentCollectionViewCell
    return cell
}

ContentCollectionViewCell

class ContentCollectionViewCell: UICollectionViewCell {
    @IBOutlet weak var userProfileImageView: UIImageView!

    required init?(coder aDecoder: NSCoder) {
        // called
        super.init(coder: aDecoder)
    }


    override init(frame: CGRect) {
        // never called
        super.init(frame: frame)
        setRoundedImage()
    }

    func setRoundedImage() {
        userProfileImageView.layer.cornerRadius = userProfileImageView.frame.width * 0.5
    }

}

但它在 ViewController 中是这样工作的。

为什么 init(frame: CGRect)in ContentCollectionViewCell 从未被调用?如果我想在 UICollectionCell 中设置预定义内容,最佳做法是什么 class?

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! ContentCollectionViewCell
    cell.userProfileImageView.layer.cornerRadius = cell.userProfileImageView.frame.width * 0.5
    return cell
}

您必须为所有单元格设置它。将此代码写入您的 cellForItemAt

cell.userProfileImageView.layer.cornerRadius = cell.userProfileImageView.frame.width * 0.5
cell.userProfileImageView!.clipsToBounds = true

希望它能奏效...!!

您应该在

中添加四舍五入的代码行
layoutSubviews()

不在 init() 中

试试这个代码我会得到帮助。

那个圆形的小区。 //舍入完整单元格

    cell.contentView.layer.cornerRadius = 2.0;
    cell.contentView.layer.borderWidth = 1.0;
    cell.contentView.layer.borderColor = UIColor.clearColor().CGColor;
    cell.contentView.layer.masksToBounds = true;

在单元格中添加以下内容Class // 单元格的圆形图像视图

class ExploreCategoryCollectionViewCell: UICollectionViewCell
{

@IBOutlet var coverImage: UIImageView!
@IBOutlet var lblCoverName: UILabel!
@IBOutlet var lblArtistName: UILabel!
@IBOutlet var lblTags: UILabel!
@IBOutlet var lblE: UILabel!

override func awakeFromNib() {
    super.awakeFromNib()

    self.coverImage.layer.cornerRadius = 5.0
    self.coverImage.layer.masksToBounds = true
}

在单元格 class 中,您可以对单元格进行任何初始设置:

class FV_Cell: UICollectionViewCell
 {
     override func awakeFromNib()
     {
         super.awakeFromNib()
           // Initialization code
    }
}