【问题标题】:Self sizing UICollectionViewCell自定尺寸 UICollectionViewCell
【发布时间】:2017-08-08 19:56:27
【问题描述】:

我正在尝试构建一个UICollectionView,它具有自我调整大小的UICollectionViewCells。我使用的是UICollectionView 而不是UITableView,因为我想在 iPhone 上使用列表视图,在 iPad 上使用网格视图。

我已经设置了一个示例项目here。

这是最简单的代码。从 Storyboard 加载的 UICollectionView。有一个UICollectionViewCell 和一个UILabel。 UILabel 具有将其固定到单元格边缘的约束。

UICollectionView 有一个UICollectionViewFlowLayout。如果我将itemSize 设置为UICollectionViewFlowLayoutAutomaticSize,则会出现约束错误。

这是我所看到的屏幕截图:

ViewController 中的代码非常简单:

class ViewController: UIViewController, UICollectionViewDataSource {

    // MARK: - Outlets

    @IBOutlet weak var collectionView: UICollectionView!
    @IBOutlet weak var collectionViewFlowLayout: UICollectionViewFlowLayout!

    // MARK: - view lifecycle

    override func viewDidLoad() {
        super.viewDidLoad()

        if #available(iOS 10.0, *) {
            // This causes constaint errors.
            //            collectionViewFlowLayout.itemSize = UICollectionViewFlowLayoutAutomaticSize
            //            collectionViewFlowLayout.estimatedItemSize = CGSize(width: 300, height: 50)
        } else {
            // Fallback on earlier versions
        }
    }

    // MARK: - UICollectionViewDataSource

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

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ItemCell", for: indexPath)

        guard let itemCell = cell as? ItemCell else {
            return cell
        }

        itemCell.label.text = "blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah"

        return cell
    }
}

【问题讨论】:

  • 你能发布你得到的错误吗?您是否尝试在单元格/标签上将translatesAutoresizingMasksIntoConstraints 设置为false?
  • translatesAutoresizingMasksIntoConstraints 在情节提要中设置为 false。我没有看到任何约束错误。
  • 当我添加 collectionViewFlowLayout.itemSize = UICollectionViewFlowLayoutAutomaticSize 然后我得到:The behavior of the UICollectionViewFlowLayout is not defined because: the item width must be less than the width of the UICollectionView minus the section insets left and right values, minus the content insets left and right values.

标签: ios uicollectionview autolayout


【解决方案1】:

在 viewDidLoad() 中添加这一行。

self.automaticallyAdjustsScrollViewInsets = false

【讨论】:

  • 我不得不改变我的 ViewController 来继承 UICollectionViewController 而不是 UIViewController 来设置它。但这没有帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-14
  • 1970-01-01
  • 2019-12-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多