我正在使用集合视图来显示配置文件图像和人员姓名的集合。所以我的单元格有一个UIImageView和一个UILabel作为子视图。我正在使用UICollectionViewDelegateFlowLayout方法:UICollectionView单元格子视图在调整collectionView:cellForItemAtIndexPath之后调整大小
collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize
根据可用空间计算单元格的大小。
所有这一切都工作正常。我在单元格的子视图中添加了约束条件,以便它们也相应地调整大小。
我遇到的问题是我想让我的UIImageViews成为圆圈。看起来像自动布局不会重新计算单元格的子视图的大小,直到我应用了该效果。相反,当我计算imageView的cornerRadius时,它仍然会说imageViews的宽度是114.0(这是故事板中的内容),无论单元格的大小如何。这会导致iPhone 5s上出现圆圈,但在任何更大的设备上只有圆角。这里是我的代码:
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("PersonCell", forIndexPath: indexPath)
configureCell(cell, atIndexPath: indexPath)
return cell
}
func configureCell(cell: UICollectionViewCell, atIndexPath indexPath: NSIndexPath) {
if let person = personAtIndexPath(indexPath) {
let imageView = cell.viewWithTag(100) as! UIImageView
let nameLabel = cell.viewWithTag(200) as! UILabel
cell.contentView.frame = cell.bounds
cell.contentView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
circularizeImageView(imageView)
imageView.image = person.profileImage
nameLabel.text = person.name
}
}
func circularizeImageView(imageView: UIImageView) {
imageView.layer.cornerRadius = (CGRectGetWidth(imageView.bounds)/2)
imageView.clipsToBounds = true
imageView.layer.borderWidth = 2.0
imageView.layer.borderColor = UIColor.whiteColor().CGColor
}
我在几个地方,以前的子视图不会调整都喜欢在这里看到:UICollectionView cell subviews do not resize
我不认为这是一个问题更多,但是你可以在configureCell()中看到我在代码中添加了修补程序,但它仍然没有帮助。
所以看起来这些子视图直到cellForItemAtIndexPath调用完成后才调整大小。有关我如何解决这个问题的任何想法?查看截图:rounded corners on UIImageViews instead of complete circles
谢谢@ bsmith11。那是我的问题。我没有将UICollectionViewCell分类(这就是为什么我使用viewWithTag())......坏决定。现在我已经将单元格分类并在layoutSubviews()中为该子类调用cicularizeImageView()。它完美的工作,我的代码更清洁,因为我的viewController不再负责单元格的布局。 – Jadsada