【问题标题】:UIcollectionview cell issue SwiftUIcollectionview 单元格问题 Swift
【发布时间】:2017-05-03 21:25:15
【问题描述】:

我有一个像这样的简单 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 模拟器上执行此代码时,我得到了这个(错误的方式:图像视图在左侧屏幕之前开始,并且宽度和高度对于约束是错误的):

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

【问题讨论】:

  • 您是否通过添加不同的设备在 xcode 预览中检查了这一点,这将帮助您检查您缺少的确切约束:这里是了解更多信息的链接pinkstone.co.uk/how-to-preview-storyboards-in-interface-builder
  • 我刚试过这个,但我在模拟器上看到了同样的结果,我不明白错误是什么
  • 您是否尝试为集合视图添加约束?所以它总是在superview里面
  • 我要为collectionview设置约束吗?
  • 如何设置collectionview的约束?

标签: ios swift xcode uicollectionview uicollectionviewcell


【解决方案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)
}
}

它有硬编码值,但你应该明白。集合视图宽度应该是每个项目的最大尺寸,所以它们不会超出框。

【讨论】: