2015-11-26 76 views
0

首先:我知道關於這個主題有成千上萬的問題,肯定其中一個問題是我的問題得到解答。但經過幾個小時的搜索後,我沒有找到解決我的問題的答案...swift imageView,collectionView,意外地發現零,同時展開一個可選值

我有一個CollectionViewController(容器內)和一個CollectionViewCell。 Cell內部有一個imageView。必須使用CollectionViewController中的按鈕更改imageView的圖像。

這裏是我的代碼:

class essenCell: UICollectionViewCell { 
@IBOutlet weak var Bild: UIImageView! 
} 

(小區)

class essenCollectionViewController: UICollectionViewController { 
[...] 
@IBAction func xyz(sender: UIButton!) { 
//following: the line with the error (unexpectedly found nil while unwrapping an Optional value) 
essenCell().Bild.image = UIImage(named: "erster") 
} 
} 

(該CollectionViewController)

首先,我想我合作將按鈕連接到單元和控制器,這在理論上工作,但在我的具體情況下不起作用。 圖像更改發生在引用parentViewController的if-Loop(在我的Controller中)內部。因爲我不能在Cell中使用這個引用,所以我需要按鈕功能在Controller中。

幫幫我!

回答

0

collectionViewCell的所有設置應該在cellForItemAtIndexPath中完成。

var buttonPressed = false 

override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { 
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("reuseCell", forIndexPath: indexPath) as! essenCell 

    if buttonPressed { 
     cell.Bild.image = UIImage(named: "erster") 
    } else { 
     cell.Bild.image = UIImage(named: "placeHolder") 

    return cell 
} 

@IBAction func xyz(sender: UIButton!) { 
    buttonPressed = true 
    collectionView?.reloadData() 
} 
+0

這工作真的很好,謝謝。但有沒有辦法使用''parentViewController''的''reloadData()''部分?我已經嘗試過'essenViewController()。collectionView?.reloadData()'但這不起作用。我得到錯誤「_uicollectionview必須使用非零布局參數swift_初始化」 –

+0

使用'NSNotificationCenter'通知向'collectionViewController'發送一個信號。這是在VC之間發送信號最簡單的方法IMO。 – Tim

+0

非常感謝。這工作! –

相關問題