【问题标题】:iOS: Constraints break when popping back to view controller after orientation is changediOS:更改方向后弹出回视图控制器时约束中断
【发布时间】:2019-08-19 14:15:19
【问题描述】:

嗨,学生们在这里学习迅速。在 iPad 上,我一直在构建一个自定义分段控件应用程序,其中纵向,分段控件位于顶部,横向,控件位于左侧。分段控件是通过在 UIView 中嵌入 collectionView 来实现的。这只是帮助我将数据源/委托方法与 viewController 分开。内容由标准的嵌套collectionView 显示。像这样:

我已经设法在这个视图控制器中处理旋转,没有任何警告或错误。我为纵向和横向启动了两个约束数组,并根据需要在viewWillTransitionToSize 中停用/激活它们。在以下情况下会出现问题: 新的视图控制器被推到这个控制器上 -> 设备被旋转 -> 弹回到这个控制器

在新视图控制器上旋转到纵向并弹回会导致“UICollectionViewFLowLayout 未定义”错误。旋转到横向不太严重,它会导致内容集合视图的大小错误。像这样:

下面是我对viewWillTransitionToSize 的实现。谢谢!我会很感激任何想法。

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    segmentedControl.collectionView.collectionViewLayout.invalidateLayout()
    segmentedControl.collectionView.reloadData()
    contentScroll.collectionViewLayout.invalidateLayout()
    contentScroll.reloadData()

    super.viewWillTransition(to: size, with: coordinator)

    NSLayoutConstraint.deactivate(p)    //deactivate constraints for portrait and landscape
    NSLayoutConstraint.deactivate(l)

    if isPortrait {
        if let layout = segmentedControl.collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
            layout.scrollDirection = .horizontal
        }

        NSLayoutConstraint.activate(p)

        DispatchQueue.main.async {    //scrolling content and segmentedControl to their correct places
            self.jumpContentViewToIndex(tabIndex: self.targetIndex, animated: false)    
            self.segmentedControl.scrollAndUpdateIndex(to: self.targetIndex)
        }
    } else {
        if let layout = segmentedControl.collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
            layout.scrollDirection = .vertical
        }

        NSLayoutConstraint.activate(l)

        DispatchQueue.main.async {    //scrolling content and segmentedControl to their correct places
            self.contentScroll.scrollToItem(at: IndexPath(item: 0, section: 0), at: .centeredHorizontally, animated: false)
            self.segmentedControl.scrollAndUpdateIndex(to: self.targetIndex)
        }
    }
}

【问题讨论】:

    标签: ios swift uicollectionview navigation autolayout


    【解决方案1】:

    在浏览了很多 stackoverflow 链接后,我找到了有用的答案 herehere。我的问题是因为位于导航堆栈中间的视图控制器在下一次布局传递之前不会重新计算其布局。您可以通过在旋转期间调用 layoutIfNeeded() 来强制更新布局,或者我所做的是将所有旋转逻辑移动到 viewDidLayoutSubviews() 并在 viewWillTransition:tosize 中设置一个标志来检查您是否需要执行旋转逻辑。

    【讨论】:

      猜你喜欢
      • 2012-12-13
      • 1970-01-01
      • 2011-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多