UICollectionView单元格问题 Swift

3
我有一个简单的集合视图控制器,就像这样:
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,并具有以下约束:

enter image description here

我的问题是:
当我在 iPhone 6 模拟器上执行此代码时,我会得到这个结果(正确的方式): enter image description here 但是,当我在 iPhone 5 模拟器上执行此代码时,我会得到这个结果(错误的方式:图像视图从屏幕左侧开始,宽度和高度与约束不符): enter image description here 我为这个问题疯狂了,但我无法解决。 你能帮帮我吗?

你在Xcode预览中添加不同的设备检查过了吗?这样可以帮助你查看你缺失的精确约束:这里是更多信息的链接http://pinkstone.co.uk/how-to-preview-storyboards-in-interface-builder/ - Shobhakar Tiwari
我刚刚尝试了这个,但是在模拟器上看到了相同的情况,我不明白出现了什么错误。 - gianni
你尝试过为集合视图添加约束吗?这样它就会始终保持在父视图内部。 - Sasha Kozachuk
如何为CollectionView设置约束? - gianni
我不明白为什么会发生这种情况?你是否将你的CollectionView单元格内容模式设置为Aspect Fill?我认为这是你的单元格问题,而不是你的ImageView。@gianni - Jitendra Modi
显示剩余3条评论
1个回答

1
你需要将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)
}
}

它有硬编码的值,但你应该能够理解。集合视图的宽度应为每个项目的最大尺寸,以便它们不会超出框架。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接