gpt4 book ai didi

Swift - cellForItemAtIndexPath 在调整图像大小时展开可选值

转载 作者:行者123 更新时间:2023-11-30 13:04:54 26 4
gpt4 key购买 nike

在快速滚动 Collection View 时,我需要动态调整 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))

有错误

"fatal error: unexpectedly found nil while unwrapping an Optional value"

如果我用这个替换它就可以工作:

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 的模式设置为单元格,如宽高比适合。

最佳答案

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

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!

所以我添加了 YourCell 例如。

关于Swift - cellForItemAtIndexPath 在调整图像大小时展开可选值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39506610/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com