我正在使用集合視圖來顯示配置文件圖像和人員姓名的集合。所以我的單元格有一個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