我一直玩弄動態UICollectionViewCell的,並已注意到在iOS 8上調用cell.contentView.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize)
在UICollectionViewCell
返回一個不正確的寬度。目前解決這個問題的唯一解決方法是明確添加寬度約束來強制單元格的寬度。下面的代碼是在細胞亞類中:UICollectionViewCell systemLayoutSizeFittingSize返回不正確的寬度
func calculatePreferredHeightForFrame(frame: CGRect) -> CGFloat {
var newFrame = frame
self.frame = newFrame
let widthConstraint = NSLayoutConstraint(item: contentView, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: CGRectGetWidth(frame))
contentView.addConstraint(widthConstraint)
self.setNeedsUpdateConstraints()
self.updateConstraintsIfNeeded()
self.setNeedsLayout()
self.layoutIfNeeded()
let desiredHeight: CGFloat = self.contentView.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize).height
newFrame.size.height = CGFloat(ceilf(Float(desiredHeight)))
contentView.removeConstraint(widthConstraint)
return CGRectGetHeight(newFrame)
}
我知道,與iOS 8和動態UICollectionViewFlowLayout的UICollectionViewCell的內容查看處理的限制不同,但有我丟失的東西嗎?需要做什麼來確保systemLayoutSizeFittingSize在單元格上使用特定的寬度?
我也遇到過這個帖子(Specifying one Dimension of Cells in UICollectionView using Auto Layout),並認爲這可能實際上使我的問題無效。也許UICollectionViewFlowLayout不是爲只有一個動態維度的單元格設計的,但這仍然不能解釋爲什麼單元格會給出不同尋常的寬度。
我有完全相同的問題,我的單元格寬度始終返回爲320(xib視圖大小)。無法真正解決它... – 2015-04-01 14:33:40
你在這個單元格中有多線內的UILabel嗎?如果是這樣,你可能有錯誤的首選最大布局寬度。 – 2015-04-23 14:26:14
@ hris.to如果你再次讀到這個問題,你會發現它與標籤無關,而是整個單元格的大小 – 2015-04-23 14:27:21