我有这个自定义的uicollectionViewCell,它在iPhone 7上起作用,但是当我在iPhone 5模拟器上运行它时,情况会很奇怪。我的收集视图有许多部分和一个部分。它看起来像一个表视图,这意味着每个单元格是全宽,它们都像表视图中一样彼此越过。由于iPhone 5中的某些原因,帧是:(-27.5,50.0,320.0,45.7143)这意味着它处于正确的宽度和高度,但在屏幕左侧开始27.5点。我这样更新小组:
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> ProfileCollectionCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! ProfileCollectionCell
let width = CGFloat((self.collectionView?.frame.width)!)
let height = width/7
cell.frame.size = CGSize(width: width, height: height)
return cell
}
我如何正确定位框架?
您不应该在cellForItemAtIndexPath
而是实现UICollectionViewDelegateFlowLayout
方法…
func collectionView(UICollectionView, layout: UICollectionViewLayout, sizeForItemAt: IndexPath) {
let width = collectionView?.frame.width ?? 0
let height = width / 7
return CGSize(width: width, height: height)
}
首先将协议添加到您的类UICollectionViewDelegateFlowLayout
中,并添加以下代码:
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
{
let width = CGFloat((self.collectionView?.frame.width)!)
let height = width/7
return CGSize(width: width, height: height)
}