[英]Swift: collectionView cell
我创建collectionView
并且有3个单元格。 我希望所有设备上所有屏幕的单元格都像这样:
但是我在iPad上有这个结果。
如何解决?
更新
我在UIViewController
添加collectionView
。 我对collectionView
有此约束:
调整我的单元格大小:
码:
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 4
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 3
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let itemsPerRow: CGFloat = 3
let itemWidth = (collectionView.bounds.width / itemsPerRow)
let itemHeight = itemWidth * 1.5
return CGSize(width: itemWidth, height: itemHeight)
}
您需要自适应地更改单元格的大小,否则该大小将不适用于所有屏幕尺寸。
您可以使用函数,在其中返回单元格大小:
return CGSize(width: 182, height: 275)
相反,应使其适应性如下:
return CGSize(width: self.view.frame.width / 3, height: self.view.frame.height)
或者,要在两者之间留出空隙,请创建一个偏移量:
let offset = 10
let width = self.view.frame.width - offset * 4 // 4 gaps
let height = self.view.frame.height - offset * 2 // 2 gaps
return CGSize(width: width / 3, height: height) // Divide into equally-sized cells
当然, self.view
可以替换为您想要单元格适合的任何容器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.