为各种iPhone屏幕尺寸动态调整UICollectionView单元格宽度的大小

时间:2017-07-03 23:17:19

标签: ios swift xcode uicollectionview uicollectionviewlayout

我有一个非常简单的UICollectionView要求。对于iPhone 6 / 6s / 7和6 / 6s / 7 Plus尺寸,两个单元必须并排显示,即每行两个单元。对于iPhone 5 / 5s / SE,它应该每行显示1个单元格。我的细胞高度几乎固定为194。

现在我在视图控制器中有这个代码来实现这一点 -

import UIKit

class ViewController: UIViewController, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource {

    @IBOutlet weak var collectionView: UICollectionView!
    var screenWidth: CGFloat!


    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = .blue

        screenWidth = collectionView.frame.width

        // Do any additional setup after loading the view, typically from a nib
        let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
//        layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 2)
        layout.itemSize = CGSize(width: screenWidth / 2, height: 194)
        layout.minimumInteritemSpacing = 0
        collectionView.collectionViewLayout = layout
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.backgroundColor = UIColor.blue
    }

    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return 1
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 20
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "customCell", for: indexPath as IndexPath) as UICollectionViewCell
        cell.backgroundColor = UIColor.white
        cell.layer.borderColor = UIColor.black.cgColor
        cell.layer.borderWidth = 0.5
        return cell
    }

}

结果输出是这个 -

enter image description here

正如你所看到的,iPhone Plus尺寸和5 / 5s / SE布局都很好,或者我应该说我对那些拥有我的东西很好,但第二个是6/6s / 7尺寸的细胞几乎互相粘在一起。我知道我有layout.minimumInteritemSpacing = 0但如果我将其增加到1,那么单元格将像第三张图像一样被按下,使用UIEdgeInsets也会导致相同的问题。

我的整个UICollectionView被固定在superview的前0,后0,左8和右8。我在SO中回顾了一些Q& As,它们与此有些相关并建议使用UICollectionViewDelegateFlowLayout sizeForItemAt函数,但我还没有能够使用它来解决这个问题。

如何解决6 / 6s / 7屏幕宽度的间距问题,使两个单元格在一条线上有一些间距?我的最终目标是在设备6及更高版本上每行有2个单元,在5s及以下设备(包括SE)每行1个单元。可以这样做吗?

1 个答案:

答案 0 :(得分:2)

在创建collectionView之前,您需要考虑edge insets s minimumInteritemSpacingsize。您应该真正实现UICollectionViewFlowLayoutDelegate方法来布局collectionView。您的width应为(screenSize - left inset - right inset - minimumInteritemSpacing) / 2

修改

为什么不根据它检查device是什么,然后return size

例如

if iPhone6 {
    return size / 2
} else {
    return size
}

要查看当前的设备,请参阅以下answer