時展開一個可選值,我需要動態調整的imagView滾動時在迅速集合視圖...斯威夫特 - cellForItemAtIndexPath調整圖像
我用這個函數獲取事件的滾動:
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])
但顯然它不會降低圖像
能幫我請???
SOLUTION: 我需要調整對象 「cell.myImage」 而不是 「cell.myImage.image」,因此解決了:
cell.myImage.frame = CGRect(x:0.0,y:0.0,width:sizeImage,height:sizeImage)
並設置ImageView的方式進樣擬合細胞。
如何創建'indexPathItem'對象? –
哦,是的......用這一行:'let indexPathItem = self.items [indexPath.item]'它是我的數組,其名稱爲圖像 – Ray13
您真的需要調整圖像大小嗎?看起來你的滾動會受到影響,爲什麼不把圖像適合imageView? –