簡體   English   中英

滾動時 CollectionViewCell 圖像不適合單元格

[英]CollectionViewCell Image does not fit in the cell while scrolling

點擊查看圖片

嗨,大家好,

我有一個圖像的collectionView。 水平滾動時,圖像不適合單元格。 我在 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
...
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM