Swift - cellForItemAtIndexPath在调整图像

时间:2016-09-15 08:41:54

标签: swift uicollectionview uicollectionviewcell resize-image

我需要在swift中滚动集合视图时动态调整imagView ...

我使用此函数来获取滚动事件:

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

                // get a reference to our storyboard cell
         let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! MyCollectionViewCell
         let indexPathItem = self.items[indexPath.item]
         if let myImage = cell.myImage{
             myImage.image = imageWithImage(UIImage(named: indexPathItem)!, scaledToSize: CGSize(width: sizeImage, height: sizeImage))
         } 

      return cell
    }

此函数用于调整图像大小:

func imageWithImage(image:UIImage,scaledToSize newSize:CGSize)->UIImage{

    UIGraphicsBeginImageContext( newSize )
    image.drawInRect(CGRect(x: 0,y: 0,width: newSize.width,height: newSize.height))
    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return newImage.imageWithRenderingMode(.AlwaysTemplate)
}
运行此行时

调试停止:

myImage.image = imageWithImage(UIImage(named: indexPathItem)!, scaledToSize: CGSize(width: sizeImage, height: sizeImage))

有错误

  

"致命错误:在打开Optional时意外发现nil   值"

如果用这个代替它,我会工作:

cell.myImage.image = UIImage(named : self.items[indexPath.item])

但显然它并没有减少图像

可以帮我吧?

解: 我需要调整大小对象" cell.myImage"而不是" cell.myImage.image"所以解决了:

  cell.myImage.frame = CGRect(x:0.0,y:0.0,width:sizeImage,height:sizeImage) 

并将imageView的模式设置为像方面适合的单元格。

1 个答案:

答案 0 :(得分:0)

您可以使用类似下面的更安全的代码来避免在解包可选值时崩溃。

equals - ZoneId.of("UTC"): false
equals - ZoneId.of("UTC").normalized(): true
equals - ZoneId.of("Z"): true
equals - ZoneId.of("+0"): true
isEqual - ZoneId.of("UTC"): true

您的func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { // get a reference to our storyboard cell let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! YourCell cell.myImage?.image = imageWithImage(UIImage(named: self.items[indexPath.item]), scaledToSize: CGSize(width: sizeImage, height: sizeImage)) return cell } func imageWithImage(image:UIImage?,scaledToSize newSize:CGSize)->UIImage?{ guard let drawImage = image else { return nil } UIGraphicsBeginImageContext( newSize ) drawImage.drawInRect(CGRect(x: 0,y: 0,width: newSize.width,height: newSize.height)) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage?.imageWithRenderingMode(.AlwaysTemplate) } 代码在行

下面不完整
cellForItemAtIndexPath

所以我添加了 let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! 例如。