我最近在一个应用程序中实现了一个 Collection View ,我遇到的唯一问题是 Collection View 在较小的设备上从 2 列变成了 1 列,两边都有很多填充
我确实尝试了几种方法,如果显示宽度小于某个数字,它会放大单元格,但它失败了,因为单元格确实放大了,但没有居中和重叠。
最佳答案
You need to calculate the cell width.Try this code.
class YourClass: UIViewController {
//MARK:-Outlets
@IBOutlet weak var yourCollectionView: UICollectionView!
//Mark:-Variables
var cellWidth:CGFloat = 0
var cellHeight:CGFloat = 0
var spacing:CGFloat = 12
var numberOfColumn:CGFloat = 2
//MARK:-LifeCycle
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
yourCollectionView.contentInset = UIEdgeInsets(top: spacing, left: spacing, bottom: spacing, right: spacing)
if let flowLayout = yourCollectionView.collectionViewLayout as? UICollectionViewFlowLayout{
cellWidth = (yourCollectionView.frame.width - (numberOfColumn + 1)*spacing)/numberOfColumn
cellHeight = cellWidth //yourCellHeight = cellWidth if u want square cell
flowLayout.minimumLineSpacing = spacing
flowLayout.minimumInteritemSpacing = spacing
}
}
extension YourClass:UICollectionViewDelegateFlowLayout{
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: cellWidth, height: cellHeight)
}
}
关于ios - Swift 3 CollectionView 缩放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40822239/