ios - didDeselectItemAt indexPath doesn't triggered when another cell is selected -
i'm trying implement feature: in app, if selected cell in uicollectionview, borders becomes blue, , if select one, previous should deselected , borders should become transparent. there methods i've written:
func collectionview(_ collectionview: uicollectionview, cellforitemat indexpath: indexpath) -> uicollectionviewcell { let cell = collectionview.dequeuereusablecell(withreuseidentifier: reuseidentifier, for: indexpath) as! chatcell /* set settings */ if globalselected[indexpath.item] { cell.circleview.layer.bordercolor = uicolor.blue.cgcolor } else { cell.circleview.layer.bordercolor = uicolor.clear.cgcolor } return cell } func collectionview(_ collectionview: uicollectionview, didselectitemat indexpath: indexpath) { //global variable maintain selection global.selectedchatpath = indexpath globalselected[indexpath.item] = true collectionview.reloaddata() } func collectionview(_ collectionview: uicollectionview, diddeselectitemat indexpath: indexpath) { if indexpath != nilpath { globalselected[indexpath.item] = false collectionview.reloaddata() } }
the nilpath indexpath(item: -1, section: 0), doesn't matter, because collectionview(_ collectionview: uicollectionview, diddeselectitemat indexpath: indexpath) isn't called. collectionview has allowselection = true , allowsmultipleselection = false properties. thankful help.
if single cell supposed selected @ same time recommend put selected index path instance variable (nil
means nothing selected)
var selectedindexpath : indexpath?
in cellforitemat
set colors depending on instance variable
func collectionview(_ collectionview: uicollectionview, cellforitemat indexpath: indexpath) -> uicollectionviewcell { let cell = collectionview.dequeuereusablecell(withreuseidentifier: reuseidentifier, for: indexpath) as! chatcell /* set settings */ if let selected = selectedindexpath, selected == indexpath { cell.circleview.layer.bordercolor = uicolor.blue.cgcolor } else { cell.circleview.layer.bordercolor = uicolor.clear.cgcolor } return cell }
in didselectitemat
reload previous , new selected cells , set selectedindexpath
new selected index path. more efficient reloading entire collection view.
func collectionview(_ collectionview: uicollectionview, didselectitemat indexpath: indexpath) { //global variable maintain selection var cellstoreload = [indexpath] if let selected = selectedindexpath { cellstoreload.append(selected) } selectedindexpath = indexpath collectionview.reloaditems(at: cellstoreload) }
diddeselectitemat
needed if want deselect cell explicitly.
Comments
Post a Comment