2016-07-29 83 views
1

我的目標是在用戶單擊單元格時創建邊框。下面如何在單擊時添加邊框到單元格

此代碼:

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { 
    print("Cell \(indexPath.row) selected") 
} 

然後我爲了使彩色邊框添加了這個代碼,但它沒有任何效果。

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { 
    let cell : MKStandItemAdd = collectionView.dequeueReusableCellWithReuseIdentifier("ItemCell", forIndexPath: indexPath) as! MKStandItemAdd 
    cell.layer.borderWidth = 7 
    cell.layer.borderColor = UIColor.blueColor().CGColor 
    print("Cell \(indexPath.row) selected") 
} 

上面的代碼仍然打印,但它沒有改變顏色。

,所以我說:

self.collectionView.reloadData() 

但現在什麼都不會發生的。它不再打印,也不會重新加載集合。

+2

後發現,不叫reloadData。重新加載特定單元格。 –

+1

當你點擊單元格時..存儲該索引並且比按照索引在'cellForItemAtIndexPath'方法中創建一個邊框 –

+0

嘗試添加'cell.layer.masksToBounds = YES;' – iSashok

回答

0

這是()簡單的解決方案,我讀1日2條評論

let cell = self.collectionView.cellForItemAtIndexPath(indexPath) 
    cell!.layer.borderWidth = 7 
    cell!.layer.borderColor = UIColor.blueColor().CGColor 
0

當您重新加載或滾動單元格時,直接設置到單元格didSelectItemAtIndexPath不會在那裏。

更好的方法是在渲染單元格的cellForRowAtIndexPath之內。

首先,我們需要有一個類變量

var selectedRow = -1 

因此,在您cellForRowAtIndexPath你需要在你didSelectRowAtIndexPath檢查所選行的索引

// check if selected 
if indexPath.row == selectedRow { 
    cell.layer.borderWidth = 7 
    cell.layer.borderColor = UIColor.blueColor().CGColor 
} 
else { 
    cell.layer.borderWidth = 0 
} 

需要重新加載電池

tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: true) 
0

cellfotitemAtIndexPath中寫

if(cell.isselected) 
{ 
cell.layer.borderWidth = 7 
    cell.layer.borderColor = UIColor.blueColor().CGColor 
} 
else 
{ 
//No border and no border color 
} 

DidSelectitemAtIndexPath

重裝你的集合視圖

相關問題