我有一个的CollectionView设置为以下,但sizeForItemAt
在collectionView!.frame.size
不一样的渲染结果。
注意:我只使用Constraints作为collectionView的布局。
任何的想法?
public override init(frame: CGRect){
super.init(frame: frame)
self.translatesAutoresizingMaskIntoConstraints = false
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0
layout.scrollDirection = .vertical
self.collectionView = UICollectionView(frame: self.frame, collectionViewLayout: layout)
self.addSubview(self.collectionView!)
self.collectionView?.translatesAutoresizingMaskIntoConstraints = false
self.collectionView!.delegate = self
self.collectionView!.dataSource = self
self.collectionView!.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "cellIdentifier")
}
public func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
collectionView!.frame.size // Tot the size of the rendered collectionView, and therefore unable to give the cell the right size???
}
发生这种情况的原因是,您的单元格UICollectionView
是在视图控制器的布局完成之前加载的。
使用约束和集合视图时,我注意到在viewDidAppear(:)
调用之前使用集合视图大小是不可靠的。
如果要相对于屏幕尺寸进行网格布局,则可以UIScreen.main.bounds.size
在该sizeForItemAt
方法中使用。
在这里,您的集合视图似乎是子UIView
类的子视图。因此,如果您不能使用屏幕尺寸,也可以在更改其视图范围后重新加载集合视图:
override var bounds: CGRect {
didSet {
if oldValue != bounds {
self.collectionView?.reloadData()
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句