I have a tableview that in each row has two buttons. If tapped on, the button background color changes.The issue is when scrolling down the table view. A Button background color has changed, that I did not even tapped on. So what I can understand is that, If i have more data to be displayed then the index is replaced by another index when i scroll because
of reusablecell. I found that tags are good way to go about it, but the tutorial and suloting I have found weren't the best. Can some explain to me how I get only that button background color to change. When one of the two button's is selected in that row and not another row.
viewcontroller
import UIKit
class ViewController: UIViewController,UITableViewDataSource, UITableViewDelegate {
var myArray:[String] = ["my", "by", "hello", "run", "Was", "sie", "very", "hungry", "code", "monkey", "dew", "big", "warm", "fuzzy", "hart", "I", "have", "every", "reason", "waiting", "some", "day", "simple", "man", "xcode"]
override func viewDidLoad() {
super.viewDidLoad()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return myArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let silly = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CellTableViewCell
silly.textLabel?.text = myArray[indexPath.row]
silly.fail.tag = indexPath.row
silly.fail.addTarget(self, action: "failed", for: .touchUpInside)
return silly
}
func tableView(_ tableView: UITableView, accessoryButtonTappedForRowWith indexPath: IndexPath) {
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}tableviewcell
import UIKit
class CellTableViewCell: UITableViewCell {
@IBOutlet weak var fail: UIButton!
@IBOutlet weak var pass: UIButton!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
@IBAction func okBtn(_ sender: Any) {
pass.backgroundColor? = UIColor.green
}
@IBAction func errorBtn(_ sender: Any) {
fail.backgroundColor? = UIColor.red
}
}