ios - UICollectionView,第一次加载时图像大小不正确

标签 ios swift uicollectionview uicollectionviewcell uicollectionviewlayout

我有一个非常简单的演示,它使用 UICollectionView 来显示图片列表,我使用自定义单元格类,其中包含一个 UIImage 和一个标签,如下所示,没有任何限制。

customize cell on storyboard

然后我在代码中设置单元格的大小如下。每行有 3 列。所有边距都设置为 10。

// Calculate size of cell
    func collectionView(collectionView: UICollectionView,
                        layout collectionViewLayout: UICollectionViewLayout,
                               sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
        let totalSpace = marginLeft + marginRight + (colomnSpacing * CGFloat(numberOfItemsPerRow - 1))
        let size = Int((collectionView.bounds.width - totalSpace) / CGFloat(numberOfItemsPerRow))

        // 20 is for label height.
        return CGSize(width: size, height: size + 20)
    }

    // Section margin, if you only have one section, then this is the CollectionView's margin.
    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
        return UIEdgeInsets(top: marginTop, left: marginLeft, bottom: marginBottom, right: marginRight) // top, left, bottom, right.
    }

    // Set row spacing
    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat {
        return rowSpacing
    }

    // Set column spacing
    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat {
        return colomnSpacing
    }

这是用于设置图像和标签大小的代码。图像的宽度占屏幕宽度的1/3(不包括列空间),高度等于宽度。标签宽度等于图像宽度,标签的高度设置为 20。

override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! SearchImageCell

        // Set image size
        cell.imageView.frame = CGRect(x: 0, y: 0, width: cell.frame.width, height: cell.frame.height - 20)
        cell.imageView.contentMode = .ScaleAspectFill


        let currentItem = self.responseArray[indexPath.row]
        let imageUrl = currentItem["imgurl"] as? String
        let url = NSURL(string: imageUrl!)

        // Load the image
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
            let data = NSData(contentsOfURL: url!)
            dispatch_async(dispatch_get_main_queue(), { 
                cell.imageView.image = UIImage(data: data!)
            })
        }

        // Set label size
        cell.imageDesc.frame = CGRect(x: 0, y: cell.imageView.frame.height, width: cell.frame.width, height: 20)

        let shujia = currentItem["shujia"] as? String
        cell.imageDesc.text = shujia!
        cell.imageDesc.font = cell.imageDesc.font.fontWithSize(14)
        cell.imageDesc.textAlignment = .Center

        return cell
    }

问题是:

当我第一次加载图片时,图片的大小不正确,如下图,你可以看到图片的高度占据了单元格的整个高度,标签没有显示出来。

enter image description here

但是,当我向下和向上滚动时(这使得单元格被重复使用),图像被调整大小,我得到了正确的结果,这就是我想要的!

enter image description here

我尝试添加一些调试代码来打印单元格/图像/标签的大小,似乎所有大小都是正确的。

cell width:  100.0
cell height:  120.0
image width:  100.0
image height:  100.0
label width:  100.0
label height:  20.0

那么,怎么了?

SO( here , here ) 上有一些类似的问题,但答案对我不起作用,比如

1. cell.layoutIfNeeded()
2. self.collectionViewLayout.invalidateLayout()
3. self.collectionView?.layoutIfNeeded()

请帮忙,如果您需要更多代码,请告诉我。

最佳答案

为您的image viewlabeltranslatesAutoresizingMaskIntoConstraints 设置为true。也许它有效。

注意:当使用 IB 时,它会将它们设置为 false

关于ios - UICollectionView,第一次加载时图像大小不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38128580/

相关文章:

iOS 8 UICollectionViewLayout 在 Swift 中切换神秘崩溃

swift - 如何在 Swift 3.1 中只调用一次函数?

swift - 距离(从 :to:)' is unavailable: Any String view index conversion can fail in Swift 4; please unwrap the optional indices

ios - 创建 UICollectionViewCell 时 subview 框架不正确

ios - iOS 6 中不显示本地通知

swift - 使用 coredata 时,在搜索栏取消按钮后 tableview.reloaddata() 不起作用

ios - UICollectionView 单元格未添加为 UICollectionView 的 subview

iphone - 隐藏或删除 UIImageView 和排列 (IOS 5)

ios - 如何在用户点击推送通知时禁用打开应用程序

objective-c - iOS:一个 View 能否看到在另一个 View 中创建的对象