【问题标题】:Change cell layout when traitCollection changestraitCollection 更改时更改单元格布局
【发布时间】:2016-10-07 02:16:47
【问题描述】:

当水平尺寸等级发生变化时,我在调整单元格的布局时遇到问题。

我的单元格有一个 stackView,我希望轴是水平的紧凑尺寸类和垂直的常规。

这是我尝试过的:

override func traitCollectionDidChange(previousTraitCollection: UITraitCollection?) {
    if previousTraitCollection?.horizontalSizeClass != traitCollection.horizontalSizeClass {
        self.collectionView?.reloadData()
    }
}

override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! MyCollectionViewCell

    switch traitCollection.horizontalSizeClass {
    case .Compact:
        cell.stackView.axis = .Horizontal
    default:
        cell.stackView.axis = .Vertical
    }

    return cell
}

但结果是并非所有单元格都会更新其布局,请参见下面的 gif。

编辑: 我已经通过在cellForItem 和单元类本身中打印来确认轴已正确更改。所以问题似乎是单元格没有重绘..

任何建议我应该如何解决这个问题?

Github Repo

【问题讨论】:

  • traitCollectionDidChange 中实现重新加载。通过这样做willChange 你的细胞仍然可以看到旧的特征集合stackoverflow.com/questions/24716136/…
  • 谢谢,但还是不行。当我在cellForItem 中注销traitCollection 时,它也会在使用 willChange 时更新,但我会根据您的建议更新我的问题。

标签: ios uicollectionview size-classes adaptive-layout


【解决方案1】:

cellForItemAtIndexPath 方法中添加对layoutIfNeeded() 的调用,以便让堆栈视图重新布局其内容:

override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! MyCollectionViewCell

    switch traitCollection.horizontalSizeClass {
    case .Compact:
        cell.stackView.axis = .Horizontal
    default:
        cell.stackView.axis = .Vertical
    }

    cell.stackView.layoutIfNeeded()

    return cell
}

【讨论】:

  • 您可以在单元格子类中的prepareForReuse() 中这样做,而不是这样做
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-10-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-25
相关资源
最近更新 更多