我有一個Horizontal CollectionView
其中有一個image view
裏面的單元格。我想要做的是設置一個默認選定的單元格。選定的單元格應該更改其圖像顏色。如果用戶選擇其他單元格,則應該選擇它,並且應該取消選擇默認選定的單元格。目前所有這些工作。但有時當我滾動並選擇一個單元格時,它的崩潰說如下。UICollectionView滾動和選擇單元格後崩潰
ERROR: unexpectedly found nil while unwrapping an Optional value
這裏是我完整的代碼
override func viewDidLoad() {
super.viewDidLoad()
self.collectionView.delegate = self
self.locationManager.delegate = self
collectionView.allowsMultipleSelection = false
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return CatNames.count
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let cell = collectionView.cellForItemAtIndexPath(indexPath) as! CategoryCell
cell.CarImage.image = UIImage(named: CatImages[indexPath.row])?.maskWithColor(UIColorFromRGB(0xEA7C6A))
cell.Name.textColor = UIColorFromRGB(0xEA7C6A)
}
func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) {
let cell = collectionView.cellForItemAtIndexPath(indexPath) as! CategoryCell
cell.CarImage.image = UIImage(named: CatImages[indexPath.row])
cell.Name.textColor = UIColor.darkGrayColor()
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! CategoryCell
cell.Name.text = CatNames[indexPath.row]
// setup selectedBackgroundView
if(cell.selected == true){
cell.CarImage.image = UIImage(named: CatImages[indexPath.row])!.maskWithColor(UIColorFromRGB(0xEA7C6A))
cell.Name.textColor = UIColorFromRGB(0xEA7C6A)
}
else{
cell.CarImage.image = UIImage(named: CatImages[indexPath.row])
cell.Name.textColor = UIColor.darkGrayColor()
}
return cell
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
let indexPath = NSIndexPath(forRow: 0, inSection: 0)
self.collectionView.selectItemAtIndexPath(indexPath, animated: false, scrollPosition: .None)
}
extension UIImage {
func maskWithColor(color: UIColor) -> UIImage? {
let maskImage = self.CGImage
let width = self.size.width
let height = self.size.height
let bounds = CGRectMake(0, 0, width, height)
let colorSpace = CGColorSpaceCreateDeviceRGB()
let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.PremultipliedLast.rawValue)
let bitmapContext = CGBitmapContextCreate(nil, Int(width), Int(height), 8, 0, colorSpace, bitmapInfo.rawValue) //needs rawValue of bitmapInfo
CGContextClipToMask(bitmapContext, bounds, maskImage)
CGContextSetFillColorWithColor(bitmapContext, color.CGColor)
CGContextFillRect(bitmapContext, bounds)
//is it nil?
if let cImage = CGBitmapContextCreateImage(bitmapContext) {
let coloredImage = UIImage(CGImage: cImage)
return coloredImage
} else {
return nil
}
}
}
亮點錯誤消息 –
並告訴我們,至少在它崩潰,在這種方法行? – Legoless
我試着在didSelectItemAtIndexPath方法中打印indexPath.row,問題是indexPath返回nil值。這是我得到的錯誤消息 - 致命錯誤:意外地發現零,同時展開一個可選值 – Bishan