UIImage缩放方面填充和剪辑子视图在UICollectionView中不起作用

Fdo*_*Fdo 13 iphone uiimageview ios uicollectionview

我有一个UICollectionView与一个包含单个UIImageView的单元格.我正在设置UIImageView frame.size以匹配单元格的frame.size,并在cellForItemAtIndexPath方法中明确要求UIImageView使用Aspect Fill和Clip Subview进行缩放:

let cell:UICollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! UICollectionViewCell

... 

var imageView = UIImageView(image: self.eventImages[indexPath.row])
imageView.frame.size = cell.frame.size
cell.contentMode = UIViewContentMode.ScaleAspectFill
cell.clipsToBounds = true
imageView.contentMode = UIViewContentMode.ScaleAspectFill
imageView.clipsToBounds = true
cell.addSubview(imageView)
Run Code Online (Sandbox Code Playgroud)

结果是伸出的图像(图像A),但当我点击(点击)图像时,它"神奇地"解析了Aspect Fill&Clip Subviews (图像B).我似乎无法理解为什么只有在点击之后才发生这种情况,而不是第一次加载图像时.它们被异步提取到服务器,但缩放仅在轻击图像后发生(也没有实现抽头功能).

注意:UICollectionView在故事板视图控制器中设置,集合视图和可重用单元都启用了Aspect Fill和Clip子视图.

图像A(错误的缩放 - 伸展,没有裁剪):

IMG A.

图像B(点击后正确缩放):

IMG B.

小智 17

这样做非常简单:

imageView.contentMode = UIViewContentMode.ScaleAspectFill;
imageView.layer.masksToBounds = YES;
Run Code Online (Sandbox Code Playgroud)

  • Swift 4 = `imageView.layer.maskToBounds = true` (3认同)

Lav*_*vvo 6

我认为你应该使用:

imageView.contentMode = UIViewContentMode.ScaleAspectFill
imageView.clipsToBounds = true
Run Code Online (Sandbox Code Playgroud)

而不是这个:

  cell.contentMode = UIViewContentMode.ScaleAspectFill
  cell.clipsToBounds = true
Run Code Online (Sandbox Code Playgroud)