gpt4 book ai didi

swift - 从纵向移动到横向时如何修复 UIcollectionView 中的项目宽度?

转载 作者:搜寻专家 更新时间:2023-11-01 05:32:16 27 4
gpt4 key购买 nike

我是 Swift 的新手,正在尝试实现一个具有“演示”模式的应用程序。我正在尝试通过使用 UICollectionView 来执行此操作,其中纵向和横向模式下的单元格是它所在框架的整个宽度和高度的一半。问题是,当我以横向或纵向模式启动应用程序时,一切正常。但是,如果我以纵向模式开始,然后“向右”旋转到横向模式,则单元格不再适合框架的宽度。

到目前为止我尝试过的是:

  • 将我的 setUpCollectionView() 函数移入和移出我的 viewDidLoad
  • 在函数中调整我的 sizeForItem
  • 调整自动布局约束

这些都没有用。

ViewController 类:UIViewController、UICollectionViewDataSource、UICollectionViewDelegate、UICollectionViewDelegateFlowLayout {

let textArray = ["Some text", "Some other text", "even more stuff", "And more stuff", "And this is more text"]

@IBOutlet weak var collectionView: UICollectionView!


override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
collectionView.dataSource = self
collectionView.delegate = self

setUpCollectionView()
}

//setUpCollectionView()

func setUpCollectionView() {

if let flowLayOut = collectionView?.collectionViewLayout as? UICollectionViewFlowLayout {
flowLayOut.scrollDirection = .horizontal
flowLayOut.minimumLineSpacing = 0
}
}

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

return textArray.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! TextCell

cell.textView.text = textArray[indexPath.row]

collectionView.isPagingEnabled = true

return cell
}

// MARK: - Make the cell fill the view size

func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {

return CGSize(width: view.frame.width, height: view.frame.height / 2)
}

感谢任何帮助。我想要的是无论是横向还是纵向,单元格始终是框架的整个宽度。

竖屏截图(正确)!( https://photos.app.goo.gl/nozLPGF8X7E1aNDE6 )

横屏截图(不正确)! https://photos.app.goo.gl/YCTJdmqVY6eKkpYS8

横屏截图(正确) https://photos.app.goo.gl/pjWyC1oZeckUuHE66

最佳答案

您可以覆盖 viewWillTransition 方法并重新加载,以便 collectionView 重新计算大小。

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)

self.collectionView?.reloadData()
}

关于swift - 从纵向移动到横向时如何修复 UIcollectionView 中的项目宽度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55487982/

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