UIcollectionview 单元格问题 Swift

UIcollectionview cell issue Swift

我有一个像这样的简单 collectionview 控制器:

class ViewController1: UICollectionViewController{

    override func viewDidLoad() {

        super.viewDidLoad()

        self.collectionView?.delegate = self
        self.collectionView?.dataSource = self

    }

    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

        return 5
    }

override func  collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "P", for: indexPath)

        return cell
    }
}

单元格中只有一个 uiimageview,它有以下限制:

我的问题是:

当我在 iPhone 6 模拟器上执行这段代码时,我得到了这个(正确的方式):

但是当我在 iPhone 5 模拟器上执行这段代码时,我得到了这个(错误的方式:图像视图在左侧屏幕之前开始并且宽度和高度相对于约束是错误的):

我为这个问题发疯了,但我无法解决。 你能帮帮我吗?

您需要扩展 ViewController1 以符合 UICollectionViewDelegateFlowLayout 协议。并实现为每个集合视图单元格设置大小的方法,如下所示:

class ViewController1: UICollectionViewController, UICollectionViewDelegateFlowLayout {
override func viewDidLoad() {

    super.viewDidLoad()

    self.collectionView?.delegate = self
    self.collectionView?.dataSource = self
}

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    print(self.collectionView!.frame)
}

override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

    return 5
}

override func  collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "P", for: indexPath)

    return cell
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
    return 0
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
    return 0
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return CGSize(width: self.collectionView!.frame.size.width, height: 120.0)
}
}

它具有硬编码值,但您应该明白了。集合视图宽度应该是每个项目的最大尺寸,这样它们就不会超出框。