[英]UICollectionViewCell size to fit for all cells on device rotation
我有一个寻呼机全屏collectionview。 设备旋转时,collectionview的第一个单元格适合横向和纵向模式下的collectionview。 但是,当我在collectionview上滚动下一个单元格时,它显示了两个单元格。 而且它不适合所有屏幕。 滚动collectionview并旋转时,如何使所有单元格大小适合collectionview。 我尝试了invalideLayout()并尝试了许多方法。 但是我无法达到。 我只想要,尽管滚动和旋转,但collectionviewcell可以在任何情况下都适合整个屏幕。
PS collectionviewcell大小应为整个屏幕大小。
public override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) {
if UIDevice.current.orientation.isLandscape,
let layout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
let width = view.frame.height
layout.itemSize = CGSize(width: width, height: UIScreen.main.bounds.width)
layout.invalidateLayout()
} else if UIDevice.current.orientation.isPortrait,
let layout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
let width = view.frame.width
layout.itemSize = CGSize(width: width , height: UIScreen.main.bounds.height)
layout.invalidateLayout()
}
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let width = view.frame.size.width
return CGSize(width: width , height: UIScreen.main.bounds.height)
}
您必须在viewWillLayoutSubviews()中编写代码。 像这样
覆盖func viewWillLayoutSubviews(){super.viewWillLayoutSubviews()
guard let flowLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout else {
return
}
if UIDevice.current.orientation == .landscapeLeft
{
flowLayout.itemSize = CGSize(width: self.view.frame.width, height: 500)
}
else if UIDevice.current.orientation == .landscapeRight
{
flowLayout.itemSize = CGSize(width: self.view.frame.width, height: 500)
}
flowLayout.invalidateLayout()
}
您可以尝试应用以下方法吗?
第一种方法
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
// YOUR CODE OR FUNCTIONS CALL HERE
}
第二方法
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.rotated), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
func rotated() {
if UIDevice.current.orientation.isLandscape,
let layout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
let width = view.frame.height
layout.itemSize = CGSize(width: width, height: UIScreen.main.bounds.width)
layout.invalidateLayout()
} else if UIDevice.current.orientation.isPortrait,
let layout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
let width = view.frame.width
layout.itemSize = CGSize(width: width , height: UIScreen.main.bounds.height)
layout.invalidateLayout()
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.