滚动时 CollectionViewCell 图像不适合单元格

CollectionViewCell Image does not fit in the cell while scrolling

大家好,

我有一个图像集合视图。水平滚动时,图像不适合单元格。我是 运行 它在 iPhone 11 pro max 中,宽度是 414。

我启用了寻呼功能。我已经尝试过了,纵横比合适,填充。它没有多大帮助。我想在滚动时使图像适合单元格

import UIKit

class ImageViewController:UIViewController,UICollectionViewDelegate, UICollectionViewDataSource {


    let cellIdentifier = "SecondImageCell"
    var images: [String] = ["1","2","3","4","5","6","7","8","9","10","11","12","13","14","15"]
    var indexpath = NSString()
    var startIndex = Int()

override func viewDidLoad() {


    super.viewDidLoad()
    indexpath = UserDefaults.standard.value(forKey: "indexPath") as! NSString
     self.paging_ref.numberOfPages = images.count

    }


    @IBOutlet weak var paging_ref: UIPageControl!
    @IBOutlet weak var secondCollectionView: UICollectionView!

    override func viewDidLayoutSubviews()
    {
        super.viewDidLayoutSubviews()
         let str = "\(indexpath)" // here i'm converting indexpath which is NSString into String
         startIndex = Int(str)!
        // here i'm converting str into integer value
        startIndex -= 1
        let indexPath = IndexPath(item: startIndex, section: 0)
        self.secondCollectionView.isPagingEnabled = true
        self.secondCollectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)
        print(indexPath)
    }


    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
     return images.count
 }

 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
     let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as! SecondCollectionViewCell
     cell.layer.shouldRasterize = true
    cell.imageView2.image = UIImage(named: images[indexPath.row])
     return cell

 }
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
           let pageIndex = round(scrollView.contentOffset.x/view.frame.width)
           self.paging_ref.currentPage = Int(pageIndex)
       }

}

我认为要么是你的约束关闭了,要么是你的内容模式不是 aspectFit

SecondCollectionViewCell: UICollectionViewCell {
...
// 1. make sure your image is constrained fully
// 2. imageView2.contentMode = .scaleAspectFit
...
}