【问题标题】:Dynamically sizing UICollectionViewCell dynamically with image upload Swift使用图像上传 Swift 动态调整 UICollectionViewCell 的大小
【发布时间】:2017-02-12 07:02:05
【问题描述】:

我想知道动态调整 UICollectionViewCell 尺寸的最佳方法(Swift 3)。我将异步图像上传到为 UICollectionView 实现适当协议的 ViewController。图像的大小都不同,因此我需要在加载 UIImageView 数据后设置单元格尺寸。我对 collectionview 本身的布局选项持开放态度,但首先我想让单元格尺寸正确。

我知道已经有一些类似的帖子,但我想知道在 Swift 3 中最合适的方法,但我还没有找到正确的方法。

是否可以在func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {} 方法中动态调整大小?或者,我可以在加载整个视图时设置自动调整大小选项吗?

这是我目前的相关方法,CollectionView的所有静态大小:

override func viewDidLoad() {
        super.viewDidLoad()
        ExitNameLabel.text = exitName
        let layout:UICollectionViewFlowLayout = UICollectionViewFlowLayout()
        layout.itemSize = CGSize(width: 120 , height: 120)
        self.imagesCollectionView.setCollectionViewLayout(layout, animated: true)
        exitLocationDetails.text = exitLocation
        imagesCollectionView.delegate = self
        imagesCollectionView.dataSource = self
    }

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

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell:ImageCollectionViewCell = imagesCollectionView.dequeueReusableCell(withReuseIdentifier: "imageCell", for: indexPath) as! ImageCollectionViewCell

        if (images_cache[imageUrls[indexPath.row]] != nil) {
            cell.imageCell.image = images_cache[imageUrls[indexPath.row]]
        } else {
            loadImage(imageUrls[indexPath.row], imageview:cell.imageCell)
        }
        return cell
    }


    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }

    func collectionView(collectionView: UICollectionView,
                        layout collectionViewLayout: UICollectionViewLayout,
                        sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
        let screenSize: CGRect = UIScreen.main.bounds
        let width = screenSize.width
        return CGSize(width: CGFloat(width), height: imagesCollectionView.bounds.size.height)
    }

感谢您帮助 iOS 新手 :)

【问题讨论】:

    标签: ios swift3 uicollectionview uicollectionviewcell


    【解决方案1】:

    试试这个

    if (images_cache[imageUrls[indexPath.row]] != nil) {
        cell.imageCell.image = images_cache[imageUrls[indexPath.row]]
        cell.imageCell.contentMode = .scaleAspectFit
    } else {
        loadImage(imageUrls[indexPath.row], imageview:cell.imageCell)
    }
    

    【讨论】:

    • 啊!我想到了。如果图像已被缓存或下载,则此方法有效。我需要的是在图像加载完成后调用self.imagesCollectionView.reloadData()。谢谢!
    猜你喜欢
    • 2018-08-04
    • 1970-01-01
    • 2011-09-18
    • 1970-01-01
    • 2011-03-16
    • 1970-01-01
    • 2013-04-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多