gpt4 book ai didi

ios - 未调用 Swift viewWillTransition

转载 作者:搜寻专家 更新时间:2023-10-31 21:52:20 26 4
gpt4 key购买 nike

我正在使用 UICollectionView 创建全屏图片库。当用户旋转设备时,我会在

中对 UICollectionView 执行更新

func viewWillTransition(调整大小:CGSize,协调器:UIViewControllerTransitionCoordinator)

我以模态方式显示此 UIViewController 并有一个 UICollectionView 占据整个屏幕。在 viewDidLoad 中,我将流布局创建为:

let flowLayout = UICollectionViewFlowLayout()
flowLayout.scrollDirection = .horizontal
flowLayout.minimumInteritemSpacing = 0
flowLayout.minimumLineSpacing = 0
photosCollectionView.isPagingEnabled = true
photosCollectionView.setCollectionViewLayout(flowLayout, animated: true)

我的尺寸也是:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return photosCollectionView.frame.size
}

当我旋转我的设备时,永远不会调用 viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator),这会导致 UICollectionViewLayout 不更新。当我旋转设备时,我确实收到消息:

The behavior of the UICollectionViewFlowLayout is not defined because: the item height must be less than the height of the UICollectionView minus the section insets top and bottom values, minus the content insets top and bottom values.

我已经在线阅读,我可以添加:

self.automaticallyAdjustsScrollViewInsets = false

UIViewController,但这没有任何影响。 UICollectionView 没有内容或部分插入。

我还在函数中调用了 super.viewWillTransition。任何人都可以帮助我解决可能导致此问题的原因吗?

最佳答案

如果您只关心设备旋转时的布局,请使用:

override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()

collectionView.collectionViewLayout.invalidateLayout()
collectionView.layoutIfNeeded()
}

来自苹果文档:

public func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator)

This method is called when the view controller's view's size ischanged by its parent (i.e. for the root view controller when itswindow rotates or is resized).If you override this method, you should either call super to propagate the change to children or manually forward the change tochildren.

我猜你可能会在那个 View 的父 View 上调用这个函数而不调用 super

解决方法还包括注册设备轮换:

override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)

NotificationCenter.default.addObserver(self, selector: #selector(deviceOrientationDidChange), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
}

override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)

NotificationCenter.default.removeObserver(self)
}

@objc func deviceOrientationDidChange(_ notification: Notification) {
let orientation = UIDevice.current.orientation
print(orientation)
}

关于ios - 未调用 Swift viewWillTransition,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42170373/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com