2015-05-22 54 views
1

我有多個UICollectionViewCells。當用戶點擊一個特定的單元格時,我希望我的應用程序更改被觸摸的單元格的背景圖像。如何更改已被點擊的UICollectionViewCell的背景圖像?

我的方法是專注於didSelectItemAtIndexPath方法。當一個單元格被觸摸時,這個方法將被調用。

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { 
    var cell: UICollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("cellIdentifier", forIndexPath: indexPath) as! UICollectionViewCell 
    cell.backgroundView = UIImageView(image: UIImage(named: "myImage")) 
} 

但是,我不能得到它的工作,但我不知道爲什麼。該問題可能與indexPath有關,即不返回正確的單元格值。我嘗試使用indexPath.row,這實際上返回一個Int號碼的單元格。

更重要的是,我還用var創建了一個新的UICollectionViewCell,但此單元格已存在。

爲什麼不更新其背景圖像?如何更改用戶已觸摸的UICollectionViewCell的背景圖像?

+0

您可以使用'cellForItemAtIndexPath'來獲取單元而不是使另一個出列? –

+0

'cellForItemAtIndexPath'是一種用於將單元放入「UICollectionView」中的方法。當你選擇一個單元格時它不會被調用。 – Cesare

+0

對不起,我不清楚。使用'cellForItemAtIndexPath'作爲獲取單元格的方法。不是完全確定swift語法,而是'collectionView.cellForItemAtIndexPath(indexPath)'。 –

回答

4

我完全同意Josh的回答,但如果使用didSelectItemAtIndexPath方法更改背景圖像,它也可以正常工作。然後,你可以使用cellForRowAtIndexPath方法返回UITableViewCell在指定indexPath,如以下方式:

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {   
    var cell = tableView.cellForRowAtIndexPath(indexPath) as UITableViewCell! 
    cell.backgroundView = UIImageView(image: UIImage(named: "photo2"))   
} 

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    var cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! UITableViewCell 
    cell.backgroundView = UIImageView(image: UIImage(named: "photo1")) 
    cell.selectionStyle = .None 
    return cell 
} 

我只是把selectionStyle.None避免亮點。我希望這對你有所幫助。

+0

謝謝維克多。我沒有使用'UITableView',而是'UICollectionView'。你可能想用'collectionView'替換'tableView'。另外,'selectionStyle'屬性在'UICollectionViews'中有效嗎? – Cesare

+0

@JoshGafni是的,你是對的,但我不回答你們中的任何一個人說,問題不是關於可重複使用的單元格或其他任何東西,我只回答一個特定的案例。 –

+0

請看我答案的第一句話 –