Reputation: 179
I have a tableView with menu options. In this menu options I have images and labels.
I would like when I click in one option the icon image change current color to another color.
var menuNameArr : Array = [String]()
var iconImageNormal : Array = [UIImage]()
var iconImageSelected : Array = [UIImage]()
@IBOutlet weak var imgLogo: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
menuNameArr = ["Menu", "Map", "Favorites", "Orders", "Settings", "Help"]
iconImageNormal = [UIImage(named: "icon-coffee-cup-gray")!, UIImage(named: "icon-placeholder-gray")!,
UIImage(named: "icon-star-gray")!, UIImage(named: "icon-shopping-cart-gray")!,
UIImage(named: "icon-settings-gray")!, UIImage(named: "icon-help-gray")!]
iconImageSelected = [UIImage(named: "icon-coffee-cup-green")!, UIImage(named: "icon-placeholder-green")!,
UIImage(named: "icon-star-green")!, UIImage(named: "icon-shopping-cart-green")!,
UIImage(named: "icon-settings-green")!, UIImage(named: "icon-help-green")!]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return menuNameArr.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MenuTableViewCell", for: indexPath) as! MenuTableViewCell
cell.imgIcon.image = iconImageNormal[indexPath.row]
cell.lblMenuName.text! = menuNameArr[indexPath.row]
cell.lblMenuName.textColor = UIColor(colorLiteralRed: 183.0/255.0, green: 183.0/255.0, blue: 183.0/255.0, alpha: 1)
return cell
}
Does anyone know how I do this?
Upvotes: 0
Views: 116
Reputation: 1084
You can add the delegate of tableview didSelectRowAtIndexPath .
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){
self.tableView.reloadData()
if let cell = tableView.cellForRow(at: indexPath) as? MenuTableViewCell {
cell.imgIcon.image = iconImageSelected[indexPath.row]
}
}
Hope it will work.
Upvotes: 1
Reputation: 2906
First, make sure you set your UITableViewDelegate, then add the following function to your class:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
if let cell = tableView.cellForRow(at: indexPath) as? MenuTableViewCell {
cell.imgIcon.image = iconImageSelected[indexPath.row]
}
}
Upvotes: 0