【问题标题】:Uicollectionview cell width issue iOS 10UIcollectionview单元格宽度问题iOS 10
【发布时间】:2016-11-06 18:20:30
【问题描述】:

我有一个集合视图控制器,我这样设置它:

class r : UICollectionViewCell {

    override var bounds: CGRect {
        didSet {
            contentView.frame = bounds
        }
    }
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "1", for: indexPath) as? r

        cell.backgroundColor = UIColor.red

        return cell


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

        return 5
    }

我希望单元格的宽度等于屏幕的宽度,因此在情节提要中我编辑了单元格的宽度:

但我有一个问题:

如果我在 iPhone 6 模拟器上执行它,我会得到这个(这是我想要在所有设备上得到的):

但如果在 iPad Pro 上执行,我会得到:

我不明白为什么。 你能帮帮我吗?

P.S 由于某些原因我不想使用 tableview

【问题讨论】:

  • 在运行时,单元格的大小与您在界面构建器中设置的大小保持一致。它不适应设备的屏幕尺寸。即使是自动布局约束也无法解决这个问题。您需要更新集合视图布局的项目大小。
  • 但是为了在运行时更新单元格的大小,我必须重写方法 sizeForItemAt 并手动计算单元格的内容大小,或者有一种方法可以使用情节提要自动执行此操作?
  • 不,你不能在情节提要中这样做。您必须在代码中手动计算。您需要告诉单元格中将显示哪些内容,然后我可以帮助您计算单元格的高度。
  • 我不明白,因为我不会自动这样做。使用 uitablewview 足以设置估计高度,然后它会根据内容自动执行,为什么使用集合视图我不这样做?你怎么帮我?
  • 嗯,就是这样。 UICollectionViews 没有这样的东西。告诉我你的单元格的内容是什么。我可能会建议你一个解决方案。

标签: ios iphone swift xcode uicollectionview


【解决方案1】:

在 iOS 10 中,函数原型存在细微差别: 这是 sizeAtItemAtIndexPath 的 Swift3.0 委托方法:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: IndexPath) -> CGSize {
        let screenRect: CGRect = UIScreen.main.bounds
        let screenWidth: CGFloat = screenRect.size.width
        let screencellHeight: CGFloat = screenRect.size.height
        let cellWidth: CGFloat = screenWidth / CGFloat(2)
        let cellHeight:CGFloat = screencellHeight / CGFloat(10.0)
        let size: CGSize = CGSize(width: cellWidth, height: cellHeight)
        return size
    }

【讨论】:

    【解决方案2】:

    如果你使用约束,那么首先你的单元格应用等宽约束和情节提要,你应该在检查编辑器中检查集合视图设置的水平和垂直。正确的所有设置..

    【讨论】:

      【解决方案3】:

      我假设您在某处为单元格设置了固定宽度。也许作为约束。动态设置:

      • 符合UICollectionViewDelegateFlowLayout

      并覆盖:

      @objc(collectionView:layout:sizeForItemAtIndexPath:)
      func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
          let desiredNumberOfCollumns: CGFloat = 1
          let width = collectionView.frame.width / desiredNumberOfCollumns
          let height = 100 // your desired height
      
          return CGSize(width: width, height: hight)
      }
      

      【讨论】:

      • 用你的方法我有固定的高度,但在单元格中会有 uilabel 和其他视图,我希望单元格具有基于内容的动态高度
      【解决方案4】:

      我认为您正在使用约束。如果是,那么您所要做的就是在约束中固定单元格的宽度。

      除非你没有改变它。无论您在哪里设置了宽度 ind 代表。它将保持不变。

      【讨论】: