ios - Change UITableViewCell selection color based on which cell was pressed -


my table view has elements sorted types: typea, typeb , typec.

i want when click on cell typea change selection color red, when type on typeb change color blue , when pressing on typec change color yellow.

right came code:

func tableview(tableview: uitableview, didselectrowatindexpath indexpath: nsindexpath) {     tableview.deselectrowatindexpath(indexpath, animated: true) }  func tableview(tableview: uitableview, willdisplaycell cell: uitableviewcell, forrowatindexpath indexpath: nsindexpath) {     guard let mode = datasource.selectedobject else {         fatalerror("willdisplaycell, no selected row?")     }      let type = modetype(rawvalue: mode.type)!     let selectioncolor = uiview() uiview     selectioncolor.backgroundcolor = type.color()     cell.selectedbackgroundview = selectioncolor } 

my issue willdisplaycell called when start app , data source empty fatal error.

how can overcome ? maybe using flag when didselectrowatindexpath called.
or there way achieve after ?

i assume have created custom uitableviewcell. create cell type enum.

 enum celltype {    case redcell    case yellowcell    case orangecell  }  //create enum property  class customcell : uitableviewcell {    var celltype:celltype = celltype.redcell //default redcell  } 

now have assign cell type in viewcontroller tableview datasource.

override func tableview(tableview: uitableview!, cellforrowatindexpath indexpath: nsindexpath!) -> uitableviewcell!  {     var cell : uitableviewcell = tableview.dequeuereusablecellwithidentifier("cell") as! customcell     cell.celltype = .redcell //your choice     return cell }  override func tableview(tableview: uitableview, shouldhighlightrowatindexpath indexpath: nsindexpath) -> bool { return true }  override func tableview(tableview: uitableview, didhighlightrowatindexpath indexpath: nsindexpath) { var cell = tableview.cellforrowatindexpath(indexpath) switch(cell.celltype) {    //handle switch case   case .redcell:        cell?.contentview.backgroundcolor = uicolor.redcolor()        cell?.backgroundcolor = uicolor.redcolor()   }  }   override func tableview(tableview: uitableview,       didunhighlightrowatindexpath indexpath: nsindexpath) { var cell = tableview.cellforrowatindexpath(indexpath) // set unhighlighted color cell?.contentview.backgroundcolor = uicolor.blackcolor() cell?.backgroundcolor = uicolor.blackcolor()  } 

edit: if have created 3 different types of cell class check tableview cell class type , change color in didhighlightrowatindexpath method.


Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -