UICollectionViewCell UIImageView忽略contentMode,导致图像溢出

问题描述 投票:0回答:2

一个相当令人沮丧的难题,其中UICollectionViewCell用UIImageView呈现,因为它是唯一的子视图。当异步调用加载图像完成该调用并调用setImage()方法时,将加载该帧。因此,通常在设置图像之前,该单元就已经处于可见状态。

但是,当在渲染单元格时将图像放到UIImageView中时,该图像不应用contentMode属性,因此图像有效地浮动并与相邻单元格重叠,滚动时会四处乱动。 >

当单元被重新使用时,即,您从断开的区域滚动离开,然后又回到该区域,则该单元再次恢复正常。]

单元加载时看到的内容:

滚动然后回到视图,单元格将正常组织。...单元格具有橙色背景色,因此可以在加载图像之前看到它们,所有单元格的确以所需的大小/位置进行渲染。这是使每个单元格溢出的图像(即使clipToBounds为true)。

是什么导致这种异常行为?图像从服务器异步加载,然后本地缓存。如果我在集合上使用.reloadData(),则单元也将自己“修复”。在首次运行后或加载时,它们似乎混合在一起了。

显示单元重用方法和初始化方法的代码示例如下:

class ThumbnailCell: UICollectionViewCell {
    var imageView: UIImageView!

    override init(frame: CGRect) {
        super.init(frame: frame)
        imageView = UIImageView(frame: contentView.bounds)
        imageView.image = nil
        imageView.clipsToBounds = true
        imageView.contentMode = .ScaleAspectFill
        imageView.setTranslatesAutoresizingMaskIntoConstraints(false)
        contentView.addSubview(imageView)
        let viewsDictionary = ["imageView" : imageView]
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[imageView]", options: .allZeros, metrics: nil, views: viewsDictionary))
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[imageView]", options: .allZeros, metrics: nil, views: viewsDictionary))
    }

    func resetImage() {
        self.imageView.contentMode = .ScaleAspectFill
        self.imageView.frame = contentView.bounds
        self.imageView.clipsToBounds = true
    }

    func setImage(image: UIImage) {
        resetImage()
        self.imageView.image = image
    }

    override func prepareForReuse() {
        super.prepareForReuse()
        self.imageView.image = nil
        resetImage()
    }
}

一个相当令人沮丧的难题,其中UICollectionViewCell用UIImageView呈现,因为它是唯一的子视图。当异步调用加载图像完成该调用并调用...

ios swift uiimageview uicollectionviewcell
2个回答
0
投票

当涉及到自动布局时,我并不是超级有用,但是我似乎内容视图具有基于图像视图的约束,当时该图像视图没有大小或框架。设置图像时,图像视图框架基于基于图像视图的内容视图。这可以解释为什么只有在第一次通过后才能正常工作。我不是100%会解决此问题的,但可以根据在初始化中传递的框架的宽度和高度为初始化中的图像视图创建框架可能有用。

setTranslatesAutoresizingMaskIntoConstraints

0
投票

我面临着完全相同的问题。解决方案来自另一个问题的answer

© www.soinside.com 2019 - 2024. All rights reserved.