ios - Swift 3 CollectionView 缩放

标签 ios swift uicollectionview

我最近在一个应用程序中实现了一个 Collection View ,我遇到的唯一问题是 Collection View 在较小的设备上从 2 列变成了 1 列,两边都有很多填充

这是比 iPhone 6 还小的显示器: enter image description here

下面是它在大于或等于 iPhone 6 的显示器上的样子: enter image description here

我确实尝试了几种方法,如果显示宽度小于某个数字,它会放大单元格,但它失败了,因为单元格确实放大了,但没有居中和重叠。

最佳答案

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/

相关文章:

iOS : pan around within a view

ios - 为 UITableView 的每一行推送不同的 UIView

ios - 如何修复错误 "Thread 1: EXC_BAD_ACCESS (code=2, address=0x7ffeeca55ff8)"

ios - RxSwift 和 UICollectionView、UITableView

ios - 如何仅在关闭特定 UIViewController 时才执行操作?

ios - 键盘动画延迟

ios - 如何将测试数据添加到PreviewProvider

ios - 在 App Store Connect 上找不到编辑版本。尝试使用 '--use_live_version true'

swift - NSNumberFormatterStyle.SpellOutStyle 中的错误?

ios - 如何在 UICollectionView 中分割部分?