UICollectionView didSelectItemAtIndexPath effects multiple cells - swift -
- swift, no storyboard, uicollectionview xib file
i running simple code update cell's background color but, more 1 cells updating.
override func viewdidload(){ super.viewdidload() // getting images library images = phasset.fetchassetswithmediatype(.image, options: nil) collectionview.allowsmultipleselection = false var nipname2 = uinib(nibname: "collectionviewcell", bundle:nil) collectionview.registernib(nipname2, forsupplementaryviewofkind: uicollectionelementkindsectionheader, withreuseidentifier: "headercell") var nipname = uinib(nibname: "myviewcell", bundle:nil) collectionview.registernib(nipname, forcellwithreuseidentifier: "cell") } func numberofsectionsincollectionview(collectionview: uicollectionview) -> int { return 1 } func collectionview(collectionview: uicollectionview, numberofitemsinsection section: int) -> int { return images.count } func collectionview(collectionview: uicollectionview, cellforitematindexpath indexpath: nsindexpath) -> uicollectionviewcell{ var cell = collectionview.dequeuereusablecellwithreuseidentifier("cell", forindexpath: indexpath) as! myviewcell cell.frame.size.width = 60 return cell } func collectionview(collectionview: uicollectionview, viewforsupplementaryelementofkind kind: string, atindexpath indexpath: nsindexpath) -> uicollectionreusableview{ switch kind { case uicollectionelementkindsectionheader: let headerview = collectionview.dequeuereusablesupplementaryviewofkind(kind, withreuseidentifier: "headercell", forindexpath: indexpath) as! collectionviewcell return headerview default: assert(false, "unexpected element kind") } } func collectionview(collectionview: uicollectionview, didselectitematindexpath indexpath: nsindexpath) { var cell = collectionview.cellforitematindexpath(indexpath) cell?.backgroundcolor = uicolor.redcolor() }
i have 300 different cells. want update third 1 randomly many other cells' background changing.
so collection , table views have strong concept of view reuse. allows large performance gains since not have keep [in case] 300 cells in memory @ same time.
when setting background color on cells, cells have potential reused when scrolling. since not explicitly setting background upon view showing, uses whatever is.
to fix set color when view requested:
func collectionview(collectionview: uicollectionview, cellforitematindexpath indexpath: nsindexpath) -> uicollectionviewcell{ // not guarantee fresh, new cell, can reused var cell = collectionview.dequeuereusablecellwithreuseidentifier("cell", forindexpath: indexpath) as! myviewcell cell.frame.size.width = 60 // explicitly set background color: cell.backgroundcolor = .whitecolor() // or whatever default color return cell }
now obvious cause additional side-effects. change background color of cell red , scroll away. when come setting white. being said, need track cells (probably storing indexes) selected , set color appropriately.
Comments
Post a Comment