我正在尝试在CollectionView上使用自动高度单元格。
我有2个不同的单元,可以工作。
旋转设备landscape
时,将更改为自动高度和宽度。有用。但是回到portrait
时,它不会:
func checkEstimatedSize(){
if(DeviceType.IS_IPAD || UIDevice.current.orientation == .landscapeLeft || UIDevice.current.orientation == .landscapeRight){
if let layout = myCollectionView.collectionViewLayout as? UICollectionViewFlowLayout {
layout.estimatedItemSize = CGSize(width: 1, height: 1)
layout.invalidateLayout()
}
}else{
if(UIDevice.current.orientation == .portrait || UIDevice.current.orientation == .portraitUpsideDown){
if let layout = myCollectionView.collectionViewLayout as? UICollectionViewFlowLayout {
//get width of CollectionView
layout.estimatedItemSize = CGSize(width: 0, height: 1)
layout.invalidateLayout()
}
}
}
}
纵向时,我希望宽度与CollectionView相同,但高度取决于单元格的内容。
我知道有一个sizeForItemAt indexPath
,但是如何检查/设置单元格(或CollectionView)的“自动高度”。
抱歉,我不是专家,所以才问专家...
谢谢。
编辑:
事实证明我第二次更改了layout.estimatedItemSize = CGSize(width: myCollectionView.frame.width, height: 0)
并可以正常工作...
但是现在我收到警告和模拟器冻结:
The behavior of the UICollectionViewFlowLayout is not defined because:
MyApp the item width must be less than the width of the UICollectionView minus the section insets left and right values, minus the content insets left and right values.
想法?
答案 0 :(得分:0)
我需要将UICollectionViewFlowLayoutAutomaticSize
设置为其他:
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator){
checkEstimatedSize()
}
func checkEstimatedSize(){
if(DeviceType.IS_IPAD || UIDevice.current.orientation == .landscapeLeft || UIDevice.current.orientation == .landscapeRight){
if let layout = myCollectionView.collectionViewLayout as? UICollectionViewFlowLayout {
layout.estimatedItemSize = CGSize(width: 1, height: 1)
layout.invalidateLayout()
}
}else{
if let layout = myCollectionView.collectionViewLayout as? UICollectionViewFlowLayout {
layout.estimatedItemSize = UICollectionViewFlowLayoutAutomaticSize
layout.invalidateLayout()
}
}
}
就像这样完美工作!
谢谢大家!