2016-09-26 134 views
2

在我的應用程序,我有UICollectionView與FlowLayout(垂直)。並在收集單元格中,我爲標題和內容的textView標籤。內容長度可能會有所不同,可能短或長。我需要實現單元格的自動調整。在視圖控制器類的viewDidLoad調整大小UICollectionViewCell

override func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes { 

    let attributes = layoutAttributes.copy() as! UICollectionViewLayoutAttributes 
    let desiredHeight = systemLayoutSizeFitting(UILayoutFittingCompressedSize).height 
    attributes.frame.size.height = desiredHeight 

    return attributes 
} 

()我寫了這個:在我CustomCell I類overrided這種方法

if let layout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout { 
    layout.estimatedItemSize = CGSize(width: view.frame.width, height: 120) 
} 

應用程序運行W/O任何錯誤,但只有滾動後的細胞大小調整,不當視圖出現在屏幕上時。有沒有什麼問題可以解決這個問題?

滾動

enter image description here

滾動

enter image description here

回答

0

之後我才相信,你有一個更新的約束問題,這就是爲什麼當你滾動內容,你有約束已經更新並獲得正確的身高。在調用systemLayoutSizeFitting(UILayoutFittingCompressedSize).height之前,您應該調用layoutIfNeeded()