当 CollectionView 只有一项时,如何使垂直 uiCollectionViewCell 位于左侧

How to make vertical uiCollectionViewCell Left side when CollectionView has only one item

当CollectionView只有一个item时,如何让垂直的uiCollectionViewCell在左边

我认为这是 iOS 中的一个错误,由于 UICollectionViewFlowLayoutAutomaticSize,它会自动将 CollectionView 中的单个单元格居中。您可以创建自己的 UICollectionViewFlowLayout

我遵循了这里给出的方法:

Stop Single UICollectionView cell Flowing to the centre of the screen

 override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
    collectionviw.delegate = self
    collectionviw.dataSource = self
    let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
    layout.sectionInset = UIEdgeInsets(top: 20, left: 5, bottom: 10, right: 2)
    layout.minimumInteritemSpacing = 0
    layout.minimumLineSpacing = 0
    collectionviw!.collectionViewLayout = layout
    collectionviw.reloadData()
}

extension ViewController: UICollectionViewDelegate, 
 UICollectionViewDataSource,UICollectionViewDelegateFlowLayout
{
func numberOfSections(in collectionView: UICollectionView) -> Int {
    return 2
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection 
section: Int) -> Int {
    return 1
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt i 
 ndexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionviw.dequeueReusableCell(withReuseIdentifier: "cell", 
for: indexPath)

    return cell
}

func collectionView(_ collectionView: UICollectionView, layout 
  collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: 
 IndexPath) -> CGSize {
          let collectionWidth = collectionView.bounds.width / 2 - 50
          return CGSize(width: collectionWidth, height: collectionWidth)
      }
  }

output