【问题标题】:UICollectionView rounded imageViewUICollectionView 圆角 imageView
【发布时间】:2017-07-25 23:25:28
【问题描述】:

我在 UICollectionView 单元中有一个 UIImageView。

我希望 uicollectionview 中每列有 2 个单元格,所以我使用了这段代码....

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    let padding: CGFloat = 25
    let collectionCellSize = collectionView.frame.size.width - padding

  return CGSize(width: collectionCellSize/2, height: collectionCellSize/2)

}

对于图像视图,我希望它是圆形的,并且此代码通常适用于其他地方..

self.accountImageView.layer.cornerRadius = frame.size.width/2
self.accountImageView.clipsToBounds = true

我试过把它放在 cellForItemAt 中,但没有成功

现在我在 CollectionView 单元类中添加了它

override func layoutSubviews() {
  super.layoutSubviews()

    self.accountImageView.layer.cornerRadius = frame.size.width/2
    self.accountImageView.clipsToBounds = true

}

图像看起来像一个瘪了的足球。

填充代码是否弄乱了圆形图像视图代码?

【问题讨论】:

  • 您是否在 IB 上为您的 UIImageView 设置了约束?
  • 是的,它是 1:1 的比例,顶部为 15,底部为 15,水平居中
  • 你确定你的 imageview 是正方形的吗?

标签: swift uiimageview uicollectionview


【解决方案1】:

您需要添加self.accountImageView.layoutIfNeeded()
并确保 imageview 的高度和宽度相等

override func layoutSubviews()
{
    super.layoutSubviews()

    self.accountImageView.layoutIfNeeded()       // add this
    self.accountImageView.layer.cornerRadius = frame.size.width/2
    self.accountImageView.clipsToBounds = true

}

【讨论】:

    【解决方案2】:

    如果你正在使用约束,那么试试这个 -

    override func layoutSubviews() {
     super.layoutSubviews()
     self.accountImageView.layoutIfNeeded() // Add this line
    
     self.accountImageView.layer.cornerRadius = frame.size.width/2
     self.accountImageView.clipsToBounds = true
    
    }
    

    【讨论】:

    • 并确保您的图像视图是正方形,即高度 = 宽度
    • 好的,所以我想测试一下,我把所有的循环代码都去掉了,然后就正常运行了。该图像是一个矩形,即使我的约束条件是宽度 50 高度 50....
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-07
    • 2012-09-15
    • 2021-06-09
    • 1970-01-01
    • 1970-01-01
    • 2020-04-02
    相关资源
    最近更新 更多