UICollectionview 单元格在滚动时发生变化

UICollectionview cells change when scrolling

我的 UICollectionview 看起来像这样:

我的 UICollectionviewCell 包含一个图像,通过设置角半径 属性 我试图让它变圆,但这是结果。我的 HeaderView 中的图像也是如此。

此外,当我滚动并随机改变外观时,我的 UICollectionviewCells 会发生变化,有些最终变成圆形,有些甚至变成菱形,有些图标变成黑色。

这是我用于 CollectionviewCell 的代码:

func collectionView(_ collectionView: UICollectionView,
                             cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    //1
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionViewCell",
                                                  for: indexPath) as! CollectionViewCell
    cell.imageView.layoutIfNeeded()
    cell.imageView.layer.masksToBounds = true
    cell.backgroundColor = UIColor.clear
    cell.imageView.tintColor = UIColor.white
    cell.imageView.layer.borderWidth = 2
    cell.imageView.layer.borderColor = UIColor.white.cgColor
    cell.imageView.layer.cornerRadius = cell.frame.width/2


    let icon = categories[indexPath.item]?.image
    cell.nameLabel.text = categories[indexPath.item]?.name
    cell.nameLabel.textColor = UIColor.white
    cell.imageView.image = icon
    let selected = categories[indexPath.item]?.selected
    if selected! {
        cell.isSelected = true
        collectionView.selectItem(at: indexPath, animated: true, scrollPosition: .centeredHorizontally)
        cell.imageView.backgroundColor = UIColor.white
        cell.imageView.tintColor = colors.colorBottom
    }


    return cell
}

这是我的 HeaderView 的代码:

//make the profileImageView round
    imageview.layer.masksToBounds = true
    imageview.layer.cornerRadius = imageview.frame.height/2
    imageview.layer.borderWidth = 4
    imageview.layer.borderColor = UIColor.white.cgColor

您不能假设您的单元格的帧在出列后重新计算,而是使用常量值:

cell.imageView.layer.cornerRadius = 16.0

1. 让你的 imageViewUICollectionViewCell round, 在 Storyboard:

  1. UICollectionViewCell'sclipToBounds设置为true
  2. UIImageView'sclipToBounds设置为true
  3. 设置imageViewaspectRatio = 1:1

cellForItemAt

中删除这两行
cell.imageView.layoutIfNeeded()
cell.imageView.layer.masksToBounds = true

2.下面一行必须负责icons becoming black

    cell.imageView.tintColor = colors.colorBottom

检查是否在选择单元格时更改 categories 数组中的 selected 状态?

3.headerView:

  1. storyboard
  2. 中设置imageViewaspectRatio=1:1
  3. 从您的代码中删除:

imageview.layer.masksToBounds = true

  1. storyboard中:将UIImageView'sclipToBounds设置为true

4. 截图:

如果您需要有关代码的任何其他帮助,请告诉我。